package com.ema.common.validate.valid;

import cn.hutool.core.util.StrUtil;
import com.ema.common.tools.sensitive.SensitiveWordService;
import com.ema.common.validate.Sensitive;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Component
public class SensitiveValidate implements ConstraintValidator<Sensitive, String> {

    private boolean required = true;

    @Resource
    private SensitiveWordService sensitiveWordService;

    @Override
    public void initialize(Sensitive constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required && StrUtil.isBlank(value)) {
            return false;
        }
        // 只要包含了敏感词将验证不通过
        return StrUtil.isBlank(value) || !sensitiveWordService.contains(value);
    }


}
