using Hotline.KnowledgeBase;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.DataPermissions;
using Hotline.Settings;
using Hotline.Share.Dtos.Knowledge;
using Hotline.Share.Enums.KnowledgeBase;
using Hotline.Share.Enums.Order;
using Hotline.Share.Requests;
using SqlSugar;
using XF.Domain.Dependency;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Hotline.Repository.SqlSugar.Knowledge
{
    public class KnowledgeRepository : BaseRepositoryWorkflow<KnowledgeBase.Knowledge>, IKnowledgeRepository, IScopeDependency
    {
        public KnowledgeRepository(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder, IServiceProvider serviceProvider) : base(uow, dataPermissionFilterBuilder, serviceProvider)
        {

        }
		/// <summary>
		/// 批量删除知识库词库
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task RemoveKnowledgeWrodBatchAsync(List<string> ids, CancellationToken cancellationToken)
		{
			await Db.Deleteable<KnowledgeWord>().In(x => x.Id, ids).ExecuteCommandAsync(cancellationToken);
		}


		public ISugarQueryable<KnowledgeBiDataListVo> DataList(KnowledgeBiDataListDto dto, CancellationToken cancellationToken)
		{
			return  Queryable(false, true, false)
				.LeftJoin<SystemOrganize>((x, o) => x.SourceOrganizeId == o.Id)
				.WhereIF(dto.CreationTimeStart.HasValue, (x, o) => x.CreationTime >= dto.CreationTimeStart)
				.WhereIF(dto.CreationTimeEnd.HasValue, (x, o) => x.CreationTime <= dto.CreationTimeEnd)
				.WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => o.Name.Contains(dto.Keyword!))
				.GroupBy((x, o) => new { x.SourceOrganizeId, o.Name, o.OrgType })
				.Select((x, o) => new KnowledgeBiDataListVo
				{
					OrgName = o.Name,
					OrgId = x.SourceOrganizeId,
					OrgType = o.OrgType,
					AddNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status == EKnowledgeStatus.OnShelf, 1, 0)),
					DeleteNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.IsDeleted, 1, 0)),
					SendBackNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status == EKnowledgeStatus.Revert, 1, 0)),
					PassNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status == EKnowledgeStatus.OnShelf, 1, 0)),
					PublicNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.IsPublic == true, 1, 0)),
				}).MergeTable();
		}
	}
}
