package cn.axzo.workflow.server.mq.inside.consumer;

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventConsumer;
import cn.axzo.framework.rocketmq.EventHandler;
import cn.axzo.workflow.common.enums.ElasticSearchEventEnum;
import cn.axzo.workflow.es.model.ProcessTaskDocument;
import cn.axzo.workflow.es.service.aggregation.AggregateProcessInstanceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ES 数据同步处理
 *
 * @author wangli
 * @since 2024-11-06 15:11
 */
@Slf4j
@Component
@AllArgsConstructor
public class ElasticSearchSyncListener implements EventHandler, InitializingBean {
    private final EventConsumer eventConsumer;
    private final HistoryService historyService;
    private final AggregateProcessInstanceService aggregateProcessInstanceService;
    @Override
    public void onEvent(Event event, EventConsumer.Context context) {
        String processInstanceId = event.normalizedData(String.class);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        // 删除指定实例的父子文档
        log.info("delete document processInstanceId: {}", processInstanceId);
        aggregateProcessInstanceService.deleteDocumentParentAndChild(processInstanceId);
        log.info("reInsert document processInstanceId: {}", processInstanceId);
        List<ProcessTaskDocument> processTaskDocuments = aggregateProcessInstanceService.syncProcessInstance(historicProcessInstance, null);
        log.info("Insert Summary: ProcessInstance Count: {}, ProcessTask Count: {}", 1, processTaskDocuments.size());
    }

    @Override
    public void afterPropertiesSet() {
        eventConsumer.registerHandler(ElasticSearchEventEnum.ELASTIC_SEARCH_SYNC.getEventCode(), this);
    }
}
