package com.ruoyi.logistics.annotation;

import cn.hutool.core.util.ReflectUtil;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 极简版字典映射工具
 * 仅处理导出DTO的字典注解字段
 */
@Component // 必须加！让Spring扫描并创建实例，@Autowired才会生效
public class SimpleDictExportUtil {

  /*  // 1. 非静态变量（静态变量无法直接@Autowired注入）
    private final RemoteDictService dictFeignClient;

    // 2. 构造器注入（推荐，比@Autowired字段注入更稳定）
    @Autowired
    public SimpleDictExportUtil(RemoteDictService dictFeignClient) {
        this.dictFeignClient = dictFeignClient;
    }*/

    @Autowired
    private ISysDictTypeService dictTypeService;


    /**
     * 处理单个对象的字典映射（非静态方法，通过Spring容器调用）
     */
    public void handleDict(Object obj) {
        if (obj == null) return;
        Field[] fields = ReflectUtil.getFields(obj.getClass());
        for (Field field : fields) {
            if (field.isAnnotationPresent(Dict.class)) {
                Dict dictAnno = field.getAnnotation(Dict.class);
                String dictType = dictAnno.value();

                try {
                    field.setAccessible(true);
                    String dictCode = (String) field.get(obj);
                    if (ObjectUtils.isEmpty(dictCode)) continue;

                    // 调用Feign客户端获取字典名称（核心）
                    String dictName = dictTypeService.getDictLabel(dictType, dictCode);
                    field.set(obj, dictName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 批量处理列表（非静态方法）
     */
    public void handleDictList(List<?> list) {
        if (list == null || list.isEmpty()) return;
        list.forEach(this::handleDict);
    }
}