package com.ruoyi.common.validRule.deviceExist;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ss.device.domain.DeviceQuery;
import com.ruoyi.ss.device.service.DeviceService;

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

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

	private DeviceExist annotation;

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

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

