package cn.axzo.workflow.core.conf;

import cn.axzo.framework.rocketmq.DefaultEventConsumer;
import cn.axzo.framework.rocketmq.EventConsumer;
import cn.axzo.framework.rocketmq.EventHandlerRepository;
import cn.axzo.framework.rocketmq.EventProducer;
import cn.axzo.framework.rocketmq.RocketMQEventProducer;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * RocketMQ 全局配置
 *
 * @author wangli
 * @since 2023/9/4 10:03
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RocketMQTemplate.class)
public class RocketMqEventConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    private static final String DEFAULT_MODULE = "workflowEngine";
    private static final String DEFAULT_EVENT = "topic_workflow_engine_";

    @Bean
    EventProducer eventProducer(RocketMQTemplate rocketMQTemplate) {
        return new RocketMQEventProducer(rocketMQTemplate,
                DEFAULT_MODULE,
                applicationName,
                EventProducer.Context.<RocketMQEventProducer.RocketMQMessageMeta>builder()
                        .meta(RocketMQEventProducer.RocketMQMessageMeta.builder()
                                .topic(DEFAULT_EVENT + activeProfile)
                                .build())
                        .syncSending(Boolean.TRUE)
                        .build(),
                null
        );
    }

    @Bean
    EventConsumer eventConsumer(EventHandlerRepository eventHandlerRepository) {
        Consumer<EventConsumer.EventWrapper> callback = (eventWrapper) -> {
            if (eventWrapper.isHandled()) {
                // 只收集被App真正消费的消息.
                //String topic = (String) eventWrapper.getExt().get(EVENT_TOPIC_KEY);

            }
        };
        return new DefaultEventConsumer(applicationName, eventHandlerRepository, callback);
    }

    /**
     * 这里注释是为了处理嵌入式和微服务兼容情况,由引入方自主配置 topic 监听
     */
    //    @Configuration(proxyBeanMethods = false)
    //    @ConditionalOnClass(RocketMQTemplate.class)
    //    @RocketMQMessageListener(topic = DEFAULT_EVENT + "${spring.profiles.active}",
    //            consumerGroup = "${spring.application.name}-${spring.profiles.active}"
    //    )
    //    public static class DefaultListener extends BaseListener implements RocketMQListener<MessageExt> {
    //
    //        @Autowired
    //        private EventConsumer eventConsumer;
    //
    //        @Override
    //        public void onMessage(MessageExt message) {
    //            super.onEvent(message, eventConsumer);
    //        }
    //    }
    @Bean
    EventHandlerRepository eventHandlerRepository() {
        return new EventHandlerRepository((ex, logText) -> {
            log.warn("MQ, handle warning {} , Exception: {}", logText, JSONUtil.toJsonStr(ex));
            if (Objects.nonNull(ex)) {
                throw new RuntimeException(ex);
            }
        });
    }
}
