package com.ruoyi.common.core.constraints;

import com.ruoyi.common.core.annotation.RegexValid;
import com.ruoyi.common.core.annotation.RegexValid;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2022/10/17 14:26
 * @Version: 1.0
 */
public class StringContentValidator implements ConstraintValidator<RegexValid, String> {

    private RegexValid regexValid;

    @Override
    public void initialize(RegexValid regexValid) {
        this.regexValid = regexValid;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // 如果value为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (StringUtils.isBlank(value)) {
            return true;
        }
        // 校验指定值是否正确
        String validValueStr = Optional.of(regexValid.value()).orElse(StringUtils.EMPTY);
        if (StringUtils.isNotBlank(validValueStr)) {
            for (String inputValue : value.split(",")) {
                boolean validRes = false; //默认校验不通过
                for (String validValue : validValueStr.split(",")) {
                    if (StringUtils.equals(inputValue, validValue)) {
                        validRes = true;
                        break;
                    }
                }
                if (!validRes) { //只要是有一次比对错误就给 校验结果赋值，多次赋值也没关系
                    return false;
                }
            }
            return true;
        }
        // 校验正则是否匹配
        String validRegex = Optional.of(regexValid.regex()).orElse(StringUtils.EMPTY);
        if (StringUtils.isNotBlank(validRegex)) {
            return Pattern.matches(validRegex, value);
        }
        return true;
    }

}
