using JiShe.CollectBus.IotSystems.LogRecord;
using JiShe.CollectBus.IotSystems.MeterReadingRecords;
using JiShe.CollectBus.MongoDB;
using JiShe.CollectBus.Repository.MeterReadingRecord;
using JiShe.CollectBus.ShardingStrategy;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories.MongoDB;
using Volo.Abp.MongoDB;

namespace JiShe.CollectBus.Repository.LogRecord
{
    public class LogRecordRepository : MongoDbRepository<CollectBusMongoDbContext, LogRecords, Guid>, ILogRecordRepository
    {

        private readonly HourShardingStrategy<LogRecords> _hourShardingStrategy;
        private readonly IMongoDbContextProvider<CollectBusMongoDbContext> _dbContextProvider;

        public LogRecordRepository(
            IMongoDbContextProvider<CollectBusMongoDbContext> dbContextProvider,
            HourShardingStrategy<LogRecords> hourShardingStrategy
            )
            : base(dbContextProvider)
        {
            _dbContextProvider = dbContextProvider;
            _hourShardingStrategy = hourShardingStrategy;
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task<IEnumerable<LogRecords>> InsertManyAsync(IEnumerable<LogRecords> entities, bool autoSave = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var collection = await GetShardedCollection(DateTime.Now);
            await collection.InsertManyAsync(entities);

            return entities;
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public async Task InsertManyAsync(List<LogRecords> entities, DateTime? dateTime)
        {
            var collection = await GetShardedCollection(dateTime);
            await collection.InsertManyAsync(entities);
        }


        /// <summary>
        /// 单条插入
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task<LogRecords> InsertAsync(LogRecords entity, bool autoSave = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var collection = await GetShardedCollection(DateTime.Now);
            await collection.InsertOneAsync(entity);
            return entity;
        }


        /// <summary>
        /// 单条插入
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public async Task<LogRecords> InsertAsync(LogRecords entity, DateTime? dateTime)
        {
            var collection = await GetShardedCollection(dateTime);
            await collection.InsertOneAsync(entity);
            return entity;
        }

        /// <summary>
        /// 单条更新
        /// </summary>
        /// <param name="filter">过滤条件，示例：Builders<LogRecords>.Filter.Eq(x => x.Id, filter.Id)</param>
        /// <param name="update">包含待更新的内容，示例：Builders<LogRecords>.Update.Set(x => x.SendHexMessage, SendHexMessage).Set(x => x.MessageId, MessageId)</param>
        /// <param name="entity">数据实体，用于获取对应的分片库</param>
        /// <returns></returns>
        public async Task<LogRecords> UpdateOneAsync(FilterDefinition<LogRecords> filter, UpdateDefinition<LogRecords> update, LogRecords entity)
        {
            var collection = await GetShardedCollection(entity.CreationTime);

            await collection.UpdateOneAsync(filter, update);
            return entity;
        }


        /// <summary>
        /// 单个获取
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<LogRecords> FirOrDefaultAsync(LogRecords entity, DateTime dateTime)
        {
            var collection = await GetShardedCollection(dateTime);
            var query = await collection.FindAsync(d => d.CreationTime == dateTime && d.AFN == entity.AFN && d.Fn == entity.Fn && d.Code == entity.Code);
            return await query.FirstOrDefaultAsync();
        }

        /// <summary>
        /// 多集合数据查询
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<List<LogRecords>> ParallelQueryAsync(DateTime startTime, DateTime endTime)
        {
            var collectionNames = _hourShardingStrategy.GetQueryCollectionNames(startTime, endTime);

            var dbContext = await DbContextProvider.GetDbContextAsync();

            var tasks = collectionNames.Select(async name =>
            {
                var collection = dbContext.Database.GetCollection<LogRecords>(name);
                var filter = Builders<LogRecords>.Filter.And(
                    Builders<LogRecords>.Filter.Gte(x => x.CreationTime, startTime),
                    Builders<LogRecords>.Filter.Lte(x => x.CreationTime, endTime)
                );
                return await collection.Find(filter).ToListAsync();
            });

            var results = await Task.WhenAll(tasks);
            return results.SelectMany(r => r).ToList();
        }

        /// <summary>
        /// 获得分片集合
        /// </summary>
        /// <returns></returns>
        private async Task<IMongoCollection<LogRecords>> GetShardedCollection(DateTime? dateTime)
        {
            var dbContext = await DbContextProvider.GetDbContextAsync();
            string collectionName = string.Empty;

            if (dateTime != null)
            {
                collectionName = _hourShardingStrategy.GetCollectionName(dateTime.Value);
            }
            else
            {
                collectionName = _hourShardingStrategy.GetCurrentCollectionName();
            }

            return dbContext.Database.GetCollection<LogRecords>(collectionName);
        }
    }
}
