package com.ruoyi.common.valid;

import com.ruoyi.common.core.domain.entity.DictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.dictType.service.DictTypeService;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 2023/10/20
 * 枚举值校验
 */
public class DictValidator implements ConstraintValidator<DictValid, String> {

	private DictValid annotation;

	@Override
	public void initialize(DictValid constraintAnnotation) {
		this.annotation = constraintAnnotation;
	}

	/**
	 * 判断是否校验成功
	 * @param value 待校验的值
	 * @return 校验结果
	 */
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		// 如果待校验的值为null，是否校验通过
		if (value == null) {
			return annotation.allowNull();
		}
		try {
			// 判断是否存在类型
			if (StringUtils.hasText(annotation.type())) {
				DictTypeService service = SpringUtils.getBean(DictTypeService.class);
				List<DictData> dictList = service.selectDictDataByType(annotation.type());
				if (CollectionUtils.isNotEmptyElement(dictList)) {
					List<String> values = dictList.stream().map(DictData::getDictValue).collect(Collectors.toList());
					return values.contains(value);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		// 如果value没有在枚举值中，校验失败
		return false;
	}
}

