using Hotline.Exams.Base;
using IdentityModel;
using SqlSugar;
using System.Linq.Expressions;
using XF.Domain.Entities;
using XF.Domain.Repository;

namespace Hotline.Repository.SqlSugar.Exam.Extensions
{
    public static class TreeExtensions
    {
        /// <summary>
        /// 获取树形结构
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="repository"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static ISugarQueryable<TEntity> GetTree<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> expression) where TEntity : class, IEntity<string>, IParentEntity, new()
        {
            var queryResult = repository.Queryable().Where(expression).Select(m => m);

            var parentQuery = repository.Queryable().InnerJoin(queryResult, (p, c) => p.Id == c.ParentId).Select(p => p);

            var childQuery = repository.Queryable().InnerJoin(queryResult, (c, p) => p.Id == c.ParentId).Select(c => c);

            var queryUnion = repository.UnionAll(queryResult, parentQuery, childQuery);

            queryUnion = queryUnion.Distinct();

            return queryUnion;
        }
    }
}
