using FlexJobApi.User.Application;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlexJobApi.Core
{
public static class PagedListUtils
{
///
/// 查询分页列表数据
///
///
///
///
///
///
public static async Task> ToPagedListAsync(this IQueryable q, PagedListQueryPageModel page, CancellationToken cancellationToken = default)
where TItem : class, new()
{
var pagedList = await q
.OrderBy(page.OrderInput)
.ToPagedListAsync(page.Page, page.Rows, cancellationToken);
var result = new PagedListQueryResult();
result.PageModel = page.Adapt();
result.PageModel.TotalCount = pagedList.TotalCount;
result.PageModel.TotalPage = pagedList.TotalPages;
result.Data = pagedList.Items.ToList();
return result;
}
///
/// 排序
///
///
///
///
///
public static IQueryable OrderBy(this IQueryable q, List orders)
{
if (orders.IsNull()) return q;
var entityType = typeof(T);
int index = 0;
var props = entityType.GetProperties();
foreach (var order in orders)
{
if (string.IsNullOrEmpty(order.Property)) continue;
// 获取排序字段的属性信息
var propertyInfo = props.FirstOrDefault(it => it.Name.Equals(order.Property, StringComparison.OrdinalIgnoreCase));
if (propertyInfo == null) throw Oops.Oh(EnumErrorCodeType.s404, $"该排序字段{order.Property}");
// 创建表达式树
var parameter = Expression.Parameter(entityType, "x");
var propertyAccess = Expression.Property(parameter, propertyInfo);
var lambda = Expression.Lambda(propertyAccess, parameter);
string methodName;
if (index == 0)
{
// 首次排序
methodName = order.Order == EnumPagedListOrder.Ascending
? "OrderBy"
: "OrderByDescending";
}
else
{
// 二次及以后排序
methodName = order.Order == EnumPagedListOrder.Ascending
? "ThenBy"
: "ThenByDescending";
}
// 调用相应的排序方法
var resultExpression = Expression.Call(
typeof(Queryable),
methodName,
[entityType, propertyInfo.PropertyType],
q.Expression,
Expression.Quote(lambda)
);
q = q.Provider.CreateQuery(resultExpression);
index++;
}
return q;
}
}
}