package com.cf.imes.framework.common.validation;

import cn.hutool.core.collection.CollUtil;
import com.cf.imes.framework.common.constants.ResourceBundleConstants;
import com.cf.imes.framework.common.core.IntArrayValuable;
import com.cf.imes.framework.common.util.i18n.core.util.ResourceBundleUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @author Gqr
 * @since 2025/8/28 15:11
 */
public class InScopeValidator implements ConstraintValidator<InScope, List<Integer>> {

    private List<Integer> values;

    private String desc;

    @Override
    public void initialize(InScope annotation) {
        IntArrayValuable[] values = annotation.value().getEnumConstants();
        if (values.length == 0) {
            this.values = Collections.emptyList();
        } else {
            this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toList());
        }
        this.desc = annotation.desc();
    }

    @Override
    public boolean isValid(List<Integer> integers, ConstraintValidatorContext constraintValidatorContext) {
        // 为空时，默认不校验，即认为通过
        if (CollUtil.isEmpty(integers)) {
            return true;
        }
        if (values.containsAll(integers)) {
            return true;
        }
        String defaultConstraintMessageTemplate = constraintValidatorContext.getDefaultConstraintMessageTemplate();
        Locale locale = LocaleContextHolder.getLocale();
        String descValue = ResourceBundleUtils.getMessage(ResourceBundleConstants.MESSAGE_ENUM_PATH, desc, desc, locale, null);
        defaultConstraintMessageTemplate = ResourceBundleUtils.getMessage(ResourceBundleConstants.MESSAGE_ENUM_PATH, defaultConstraintMessageTemplate, defaultConstraintMessageTemplate, locale, descValue);;

        // 校验不通过，自定义提示语句（因为，注解上的 value 是枚举类，无法获得枚举类的实际值）
        constraintValidatorContext.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
        constraintValidatorContext.buildConstraintViolationWithTemplate(defaultConstraintMessageTemplate).addConstraintViolation(); // 重新添加错误提示语句
        return false;
    }
}
