package com.ruoyi.common.validRule.apiPriceExist;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ss.apiPrice.domain.ApiPriceQuery;
import com.ruoyi.ss.apiPrice.service.ApiPriceService;

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

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

	private ApiPriceExist annotation;

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

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

