package com.ruoyi.common.validRule.modelExist;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ss.model.domain.SmModelQuery;
import com.ruoyi.ss.model.service.ModelService;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 2023/10/20
 * 枚举值校验
 */
public class ModelExistValidator implements ConstraintValidator<ModelExist, Long> {

	private ModelExist annotation;

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

	/**
	 * 判断是否校验成功
	 * @param value 待校验的值
	 * @return 校验结果
	 */
	@Override
	public boolean isValid(Long value, ConstraintValidatorContext context) {
		// 如果待校验的值为null，是否校验通过
		if (value == null) {
			return annotation.allowNull();
		}
		try {
			ModelService service = SpringUtils.getBean(ModelService.class);
			SmModelQuery query = new SmModelQuery();
			query.setModelId(value);
			return service.selectOne(query) != null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

