package vip.xiaonuo.coldchain.core.service.beanprocessor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import vip.xiaonuo.coldchain.core.service.dataprocess.handler.AbstractColdChainDataHandler;
import vip.xiaonuo.coldchain.core.service.dataprocess.handler.ColdChainDataHandler;
import vip.xiaonuo.coldchain.core.service.dataprocess.handler.ColdChainHandlerRegistry;

/**
 * @author jackzhou
 * @version 1.0
 * @project jfcloud-coldchain
 * @description 注册非AbstractColdChainDataHandler的数据处理器
 * @date 2024/11/12 13:21:44
 */

@Component
@Slf4j
public class ColdChainDataHandlerBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        // 判断 Bean 是否实现了 ColdChainDataHandler 接口，并且不是 AbstractColdChainDataHandler 的子类
        if (bean instanceof ColdChainDataHandler && !(bean instanceof AbstractColdChainDataHandler)) {
            ColdChainDataHandler handler = (ColdChainDataHandler) bean;
            // 防止重复注册
            if (!ColdChainHandlerRegistry.isHandlerRegistered(handler.getDataClass())) {
                handler.registerHandler();  // 自动注册
                log.info("冷链数据自动注册处理器: {}", handler.getDataClass().getSimpleName());
            } else {
                log.warn("冷链数据处理器已经注册: {}", handler.getDataClass().getSimpleName());
            }
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;  // 不做修改，直接返回
    }
}

