using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using YGNT.Infrastructure.ExceptionExtension;
using YGNT.Infrastructure.Model;

namespace YGNT.Infrastructure.Extension
{
    public static class QueryableExtension
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static IQueryable<T> Paging<T>(this IQueryable<T> queryable, QueryBaseDto query) where T : class
        {
            if (query.QueryAll)
                return queryable;
            return queryable.Paging(query.PageSize, query.PageIndex);
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static IQueryable<T> Paging<T>(this IQueryable<T> queryable, int pageSize, int pageIndex) where T : class
        {
            return queryable
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize);
        }

        public static async Task<TSource> GetSingleAsync<TSource>(
            this IQueryable<TSource> source,
             Expression<Func<TSource, bool>> predicate, string name = "数据")
        {
            var data = await source.SingleOrDefaultAsync(predicate);
            if (data == null)
                throw new NotExistException($"当前{name}不存在");
            return data;
        }

        /// <summary>
        /// 检查是否存在 不存在抛出异常
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="predicate"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static async Task IsExistAsync<TSource>(
             this IQueryable<TSource> source,
            Expression<Func<TSource, bool>> predicate, string name = "数据")
        {
            var isExist = await source.AnyAsync(predicate);
            if (!isExist)
                throw new NotExistException($"当前{name}不存在");
        }

    }
}