package com.ruoyi.common.validRule.deviceNoExist;

import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.common.utils.spring.SpringUtils;

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

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

	private DeviceNoExist annotation;

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

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

