package cn.axzo.workflow.server.controller.listener.doc;

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventProducer;
import cn.axzo.workflow.common.enums.DocChangeEventEnum;
import cn.axzo.workflow.core.conf.CustomEventManager;
import cn.axzo.workflow.core.engine.event.DocChangeEvent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * Application 内的文档变更事件处理器，通过该接口广播 MQ
 *
 * @author wangli
 * @since 2025-04-07 17:10
 */
@Component
public class DocChangeListener {
    @Resource
    private CustomEventManager eventManager;
    @Resource
    private EventProducer<?> eventProducer;
    @Value("${sendMq:true}")
    private Boolean sendMQ;

    @TransactionalEventListener(value = DocChangeEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void handleEvent(DocChangeEvent event) {
        try {
            sendMessageQueue(event);
        } finally {
            eventManager.eventProcessed();
        }
    }


    public void sendMessageQueue(DocChangeEvent event) {
        if (!sendMQ) {
            return;
        }
        eventProducer.send(Event.builder()
                .shardingKey(event.getKey())
                .eventCode(DocChangeEventEnum.DOC_CHANGE.getEventCode())
                .targetId(event.getKey())
                .targetType(event.getKey())
                .data(JSON.toJSONString(event, SerializerFeature.WriteMapNullValue))
                .build());
    }
}
