using System.Linq.Expressions;
using Hotline.Repository.SqlSugar.DataPermissions;
using Hotline.Repository.SqlSugar.Extensions;
using SqlSugar;
using XF.Domain.Entities;
using XF.Domain.Repository;

namespace Hotline.Repository.SqlSugar;

public class BaseRepositoryWorkflow<TEntity> : BaseRepository<TEntity>, IRepositoryWorkflow<TEntity>
    where TEntity : class, IEntity<string>, IHasCreationTime, IDataPermission, IWorkflow, new()
{
    private readonly IDataPermissionFilterBuilder _dataPermissionFilterBuilder;

    protected BaseRepositoryWorkflow(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder, IServiceProvider serviceProvider) : base(uow, dataPermissionFilterBuilder, serviceProvider)
    {
        _dataPermissionFilterBuilder = dataPermissionFilterBuilder;
    }

    public ISugarQueryable<TEntity> Queryable(bool permissionVerify = false, bool includeDeleted = false, bool canView = true, bool? hasHandled = null, bool? isAdmin = false,bool? hasHandledStep = null)
    {
        if (includeDeleted)
            Db.QueryFilter.Clear();

        var query = Db.Queryable<TEntity>();
        if (permissionVerify)
            query = query.DataPermissionFiltering(_dataPermissionFilterBuilder);

        if (canView && isAdmin != true)
            query = query.WorkflowViewFiltering(_dataPermissionFilterBuilder);

        if (canView && isAdmin == true)
            query = query.WorkflowViewFilteringAdmin();

        if (hasHandled.HasValue)
            query = query.WorkflowHandleFiltering(_dataPermissionFilterBuilder, hasHandled.Value, isAdmin);
        if (hasHandledStep.HasValue)
            query = query.WorkflowHandleStepFiltering(_dataPermissionFilterBuilder, hasHandledStep.Value, isAdmin);

		return query.Clone();
    }

    public async Task<string> AddAsync(TEntity entity, CancellationToken cancellationToken = default)
    {
        entity.InitDatePermission(_dataPermissionFilterBuilder.DataPermissionManager);
            //.AssignToCreator(_dataPermissionFilterBuilder.DataPermissionManager);
        var excEntity = await Db.Insertable(entity).ExecuteReturnEntityAsync();
        return excEntity.Id;
    }

    /// <summary>
    /// 批量插入（应用场景：小数据量，超出1万条建议另行实现）
    /// </summary>
    /// <param name="entities"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task AddRangeAsync(List<TEntity> entities, CancellationToken cancellationToken = default)
    {
        entities.ForEach(d => d.InitDatePermission(_dataPermissionFilterBuilder.DataPermissionManager));
                //.AssignToCreator(_dataPermissionFilterBuilder.DataPermissionManager));
        await Db.Insertable(entities).ExecuteCommandAsync();
    }
}