using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Domain.Entities;
using Abp.Linq.Extensions;
using Microsoft.EntityFrameworkCore;

namespace YGNT.Infrastructure.Extension
{
    public static class ResultExtension
    {
        /// <summary>
        /// 获取查询列表
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="search"></param>
        /// <param name="select"></param>
        /// <returns></returns>
        public static async Task<PagedResultDto<TResult>> GetResultAsync<TResult, TEntity>(this IQueryable<TEntity> queryable, PagedResultRequestDto search, Expression<Func<TEntity, TResult>> select) where TEntity : IEntity
        {
            var result = new PagedResultDto<TResult>()
            {
                TotalCount = await queryable.CountAsync(),
                Items = await queryable.PageBy(search.SkipCount, search.MaxResultCount)
                    .Select(select)
                   .ToListAsync()
            };
            return result;
        }

        /// <summary>
        /// 获取查询列表
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TPrimaryKey"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="search"></param>
        /// <param name="select"></param>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public static async Task<PagedResultDto<TResult>> GetResultAsync<TResult, TEntity, TPrimaryKey>(this IQueryable<TEntity> queryable, PagedResultRequestDto search, Expression<Func<TEntity, TResult>> select, TPrimaryKey primaryKey)
            where TEntity : IEntity<TPrimaryKey>
        {
            var result = new PagedResultDto<TResult>()
            {
                TotalCount = await queryable.CountAsync(),
                Items = await queryable.PageBy(search.SkipCount, search.MaxResultCount)
                    .Select(select)
                    .ToListAsync()
            };
            return result;
        }
    }
}