using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace YGNT.Infrastructure.Extension
{
    public static class RandomExtension
    {
        /// <summary>
        /// 获取随机实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="queryable"></param>
        /// <returns></returns>
        public static async Task<TEntity> GetRandomAsync<TEntity>(this IQueryable<TEntity> queryable)
            where TEntity : IEntity<long>
        {
            var maxId = await queryable.MaxAsync(x => x.Id);
            var random = RandomHelper.GetRandomOf(0d, 1d);
            var randomId = Math.Round(maxId * random, 3, MidpointRounding.AwayFromZero);
            var entity = await queryable.Where(x => x.Id >= randomId)
                .FirstOrDefaultAsync();
            return entity;
        }

        /// <summary>
        /// 获取随机实体列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public static async Task<List<T>> GetRandomListAsync<T>(this IQueryable<T> queryable, int count)
            where T : IEntity<long>
        {
            var entities = new List<T>();
            for (int i = 0; i < count; i++)
            {
                queryable = queryable.Where(x => !entities.Contains(x));
                var entity = await queryable.GetRandomAsync();
                entities.Add(entity);
            }
            return entities;
        }

    }
}