using Atomx.Admin.Client.Models;
using Atomx.Common.Enums;
using FluentValidation;

namespace Atomx.Admin.Client.Validators
{
    public class CategoryModelValidator : AbstractValidator<CategoryModel>
    {
        public CategoryModelValidator()
        {
            RuleFor(p => p.Name).NotEmpty().WithMessage("名称不能为空");
            RuleFor(p => p.ParentId).Must((p,id)=> ValidateParent(id,p)).WithMessage("不能选择自己做上级分类");
        }

        private bool ValidateParent(long parentId, CategoryModel model)
        {
            if (model.Id == parentId && model.Id > 0)
            {
                return false;
            }
            return true;
        }

        public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
        {
            var result = await ValidateAsync(ValidationContext<CategoryModel>.CreateWithOptions((CategoryModel)model, x => { x.IncludeProperties(propertyName); }));
            if (result.IsValid)
                return Array.Empty<string>();
            return result.Errors.Select(e => e.ErrorMessage);
        };
    }
}
