using JiShe.CollectBus.IotSystems.MeterReadingRecords;
using JiShe.CollectBus.MongoDB;
using JiShe.CollectBus.ShardingStrategy;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories.MongoDB;
using Volo.Abp.MongoDB;
using Volo.Abp.MongoDB.DistributedEvents;
using Volo.Abp.Timing;
using static System.Net.Mime.MediaTypeNames;

namespace JiShe.CollectBus.Repository.MeterReadingRecord
{
    /// <summary>
    /// 抄读记录仓储
    /// </summary>
    public class MeterReadingRecordRepository : MongoDbRepository<CollectBusMongoDbContext, MeterReadingRecords, Guid>, IMeterReadingRecordRepository
    {

        private readonly IShardingStrategy<MeterReadingRecords> _shardingStrategy;
        private readonly IMongoDbContextProvider<CollectBusMongoDbContext> _dbContextProvider;

        public MeterReadingRecordRepository(
            IMongoDbContextProvider<CollectBusMongoDbContext> dbContextProvider,
            IShardingStrategy<MeterReadingRecords> shardingStrategy
            )
            : base(dbContextProvider)
        {
            _dbContextProvider = dbContextProvider;
            _shardingStrategy = shardingStrategy;
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task<IEnumerable<MeterReadingRecords>> InsertManyAsync(IEnumerable<MeterReadingRecords> 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<MeterReadingRecords> 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<MeterReadingRecords> InsertAsync(MeterReadingRecords 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<MeterReadingRecords> InsertAsync(MeterReadingRecords entity, DateTime? dateTime)
        {
            var collection = await GetShardedCollection(dateTime);
            await collection.InsertOneAsync(entity);
            return entity;
        }

        /// <summary>
        /// 单条更新
        /// </summary>
        /// <param name="filter">过滤条件，示例：Builders<MeterReadingRecords>.Filter.Eq(x => x.Id, filter.Id)</param>
        /// <param name="update">包含待更新的内容，示例：Builders<MeterReadingRecords>.Update.Set(x => x.Processed, true).Set(x => x.ProcessedTime, Clock.Now)</param>
        /// <param name="entity">数据实体，用于获取对应的分片库</param>
        /// <returns></returns>
        public async Task<MeterReadingRecords> UpdateOneAsync(FilterDefinition<MeterReadingRecords> filter, UpdateDefinition<MeterReadingRecords> update, MeterReadingRecords 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<MeterReadingRecords> FirOrDefaultAsync(MeterReadingRecords entity, DateTime? dateTime)
        {
            var collection = await GetShardedCollection(dateTime);
            var query = await collection.FindAsync(d => d.CreationTime == dateTime.Value && d.AFN == entity.AFN && d.Fn == entity.Fn && d.FocusAddress == entity.FocusAddress);
            return await query.FirstOrDefaultAsync();
        }

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


            var tasks = collectionNames.Select(async name =>
            {
                var collection = database.GetCollection<MeterReadingRecords>(name);
                var filter = Builders<MeterReadingRecords>.Filter.And(
                    Builders<MeterReadingRecords>.Filter.Gte(x => x.CreationTime, startTime),
                    Builders<MeterReadingRecords>.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<MeterReadingRecords>> GetShardedCollection(DateTime? dateTime)
        {
            var database = await GetDatabaseAsync();
            string collectionName = string.Empty;

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

            return database.GetCollection<MeterReadingRecords>(collectionName);
        }

    }
}
