package com.fizz.business.service.hanle;

import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.OpcMessage;
import com.fizz.business.service.OpcMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class OpcMessageDispatcher {

    private final Map<OpcMessageType, OpcMessageHandler<? extends OpcMessage>> handlerMap = new HashMap<>();

    @Autowired
    public OpcMessageDispatcher(ApplicationContext context) {

        Collection<OpcMessageHandler> handlers = context.getBeansOfType(OpcMessageHandler.class).values();

        for (OpcMessageHandler handler : handlers) {

            // ⭐⭐ 从代理类中获取注解的正确方式
            OpcMessageHandlerType annotation =
                    AnnotationUtils.findAnnotation(handler.getClass(), OpcMessageHandlerType.class);

            if (annotation == null) {
                throw new IllegalStateException(
                        handler.getClass().getSimpleName() + " 未标注 @OpcMessageHandlerType");
            }

            handlerMap.put(annotation.value(), handler);
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends OpcMessage> void dispatch(OpcMessageType type, T message) {
        OpcMessageHandler<T> handler = (OpcMessageHandler<T>) handlerMap.get(type);
        if (handler != null) {
            handler.handle(message);
        } else {
            log.warn("未注册的 OPC 消息类型: {}", type);
        }
    }
}
