package cn.axzo.workflow.core.engine.listener;

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.common.utils.ContextHolder;
import cn.axzo.workflow.core.service.ExtAxReProcDefService;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 记录流程部署扩展信息
 *
 * @author wangli
 * @since 2023/11/18 21:21
 */
@Slf4j
@Component
public class EngineDeploymentEventListener extends AbstractFlowableEngineEventListener {
    @Resource
    private ExtAxReProcDefService extAxReProcDefService;

    @Override
    protected void entityCreated(FlowableEngineEntityEvent event) {

        if (FlowableEngineEventType.ENTITY_CREATED.equals(event.getType())) {
            if (event.getEntity() instanceof ProcessDefinition) {
                // 获取操作人信息（假设在这里设定为固定值，你可以根据实际情况获取操作人信息）

                // 记录操作人和部署信息到自定义表中
                saveDeploymentInfo((ProcessDefinition) event.getEntity());
            }
        }
    }

    private void saveDeploymentInfo(ProcessDefinition definition) {
        log.info("thread Name: {}, hashCode: {}", Thread.currentThread().getName(), Thread.currentThread().hashCode());
        BpmnTaskDelegateAssigner operatorAssigner = ContextHolder.get();
        log.info("操作人：{}", JSONUtil.toJsonStr(operatorAssigner));
        if (Objects.nonNull(operatorAssigner)) {
            extAxReProcDefService.create(definition.getId(), operatorAssigner);
        }
    }
}
