package com.ruoyi.common.validRule.contentArea;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class ContentTypeAreaValidator implements ConstraintValidator<ContentTypeAreaCheck, Object> {

    private String contentTypeField;     // contentType 字段名
    private int contentTypeValue;       // 触发校验的 contentType 值（2）
    private String areaIdField;         // areaId 字段名

    @Override
    public void initialize(ContentTypeAreaCheck constraintAnnotation) {
        // 初始化注解配置
        contentTypeField = constraintAnnotation.contentTypeField();
        contentTypeValue = constraintAnnotation.contentTypeValue();
        areaIdField = constraintAnnotation.areaIdField();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        try {
            Field contentTypeField = object.getClass().getDeclaredField(this.contentTypeField);
            contentTypeField.setAccessible(true);
            Integer contentType = (Integer) contentTypeField.get(object);


            if (contentType == null || contentType != contentTypeValue) {
                return true;
            }

            Field areaIdField = object.getClass().getDeclaredField(this.areaIdField);
            areaIdField.setAccessible(true);
            Object areaId = areaIdField.get(object);

            return areaId != null && !areaId.toString().trim().isEmpty();

        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("校验字段不存在或无法访问", e);
        }
    }
}
