package com.yifu.cloud.plus.v1.yifu.common.security.util.dict;

import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author fxj
 * @Date 2022/6/22
 * @Description
 * @Version 1.0
 */
public class DictValuesConstraintValidator implements ConstraintValidator<DictValidator,String> {
	Set<String> values = new HashSet<>();

	@Override
	public void initialize(DictValidator constraintAnnotation) {
		/*String readConverterExp = constraintAnnotation.readConverterExp();
		values.add(readConverterExp);*/
		// 获取注解中传入的values信息
		String dictType= constraintAnnotation.dictType();
		Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(dictType);
		// 遍历values信息，放到set中
		if (Common.isNotNull(dicObj)){
			values.addAll(dicObj.keySet());
		}
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
		// 当用户传进来的值符合给定的值才允许通过（return true）
		return values.contains(value);
	}
}
