using Hotline.Repository.SqlSugar.DataPermissions;
using Hotline.Settings.Hotspots;
using Hotline.Settings.TimeLimits;
using SqlSugar;
using XF.Domain.Dependency;

namespace Hotline.Repository.SqlSugar.System
{
    public class EventCategoryRepository : BaseRepository<EventCategory>, IEventCategoryRepository, IScopeDependency
    {
        public EventCategoryRepository(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder, IServiceProvider serviceProvider) : base(uow, dataPermissionFilterBuilder, serviceProvider)
        {
        }

        public async Task<(string,string)> GetNewEventCodeAsync(string? parentId,string name)
        {
            Db.QueryFilter.Clear();
            if (string.IsNullOrEmpty(parentId))
            {
                //一级
                var maxCode = await Db.Queryable<EventCategory>()
                    .Where(d => d.Id.Length == 2)
                    .MaxAsync(d => d.Id);
                if (string.IsNullOrEmpty(maxCode))
                {
                    return ("01",name);
                }
                else
                {
                    return ((int.Parse(maxCode) + 1).ToString("00"),name);
                }
            }
            else
            {

                //查询是否存在下级
                var model = await Db.Queryable<EventCategory>()
                    .OrderByDescending(x => x.Id)
                    .FirstAsync(x => x.ParentId == parentId);

                //如果存在下级
                if (model != null)
                {
                    return ((int.Parse(model.Id) + 1).ToString("00"), model.EventFullName + "-" + name);
                }
                //如果不存在下级
                else
                {
                    var parentModel = await Db.Queryable<EventCategory>()
                        .FirstAsync(x => x.Id == parentId);
                    return (parentModel.Id + "01", parentModel.EventFullName + "-" + name);
                }
            }
        }
    }
}
