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

import com.yd.oss.feign.annotation.PdfField;
import com.yd.oss.service.service.FieldValueProvider;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * 支持注解和 Map 的通用字段值提供器
 */
@Component
public class AnnotationFieldValueProvider<T> implements FieldValueProvider<T> {

    @Override
    @SuppressWarnings("unchecked")
    public String getFieldValue(T object, String fieldName) {
        try {
            // 如果对象是 Map 类型
            if (object instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) object;
                Object value = map.get(fieldName);
                return value != null ? value.toString() : "";
            }

            // 如果是普通 Java 对象，使用注解方式
            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 "";
        }
    }
}
