package com.yd.oss.service.service.impl;

import com.yd.oss.service.annotation.PdfField;
import com.yd.oss.service.service.FieldValueProvider;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 使用注解实现通用字段值提供器
 * @param <T>
 */
@Component
public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> {
    
    @Override
    public String getFieldValue(T object, String fieldName) {
        try {
            // 获取所有字段
            Field[] fields = object.getClass().getDeclaredFields();
            
            for (Field field : fields) {
                PdfField annotation = field.getAnnotation(PdfField.class);
                if (annotation != null && annotation.value().equals(fieldName)) {
                    field.setAccessible(true);
                    Object value = field.get(object);
                    return value != null ? value.toString() : "";
                }
            }
            
            // 如果没有找到注解，尝试使用字段名
            try {
                Field field = object.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(object);
                return value != null ? value.toString() : "";
            } catch (NoSuchFieldException e) {
                return "";
            }
            
        } catch (Exception e) {
            return "";
        }
    }
}
