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

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventProducer;
import cn.axzo.workflow.common.enums.ElasticSearchEventEnum;
import cn.axzo.workflow.core.common.context.TaskOperationContext;
import cn.axzo.workflow.core.listener.AbstractBpmnEventListener;
import cn.axzo.workflow.core.listener.BpmnTaskEventListener;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 同步任务相关数据至 ES
 *
 * @author wangli
 * @since 2024-10-16 16:50
 */
@Slf4j
@Component
@Scope("prototype")
public class SyncToEsTaskEvent_104_Listener extends AbstractBpmnEventListener<TaskOperationContext> implements BpmnTaskEventListener, Ordered {
    @Resource
    private EventProducer<?> eventProducer;
    @Value("${sendMq:true}")
    private Boolean sendMQ;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 104;
    }

    /**
     * 用户任务已指派审核人
     *
     * @param delegateTask
     */
    @Override
    public void onAssigned(DelegateTask delegateTask) {
        sendMessageQueue(delegateTask.getProcessInstanceId(), ElasticSearchEventEnum.ELASTIC_SEARCH_SYNC);
    }

     private void sendMessageQueue(String processInstanceId, ElasticSearchEventEnum eventEnum) {
        if (!sendMQ) {
            return;
        }
        eventProducer.send(Event.builder()
                .shardingKey(processInstanceId)
                .eventCode(eventEnum.getEventCode())
                .targetId(processInstanceId)
                .targetType(processInstanceId)
                .data(processInstanceId)
                .build());
    }

}
