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 com.alibaba.fastjson.JSON;
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;

/**
 * 记录流程部署扩展信息
 *
 * @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) {
        BpmnTaskDelegateAssigner operatorAssigner = ContextHolder.get();
        log.info("操作人：{}", JSON.toJSONString(operatorAssigner));

        // TODO 创建 ext_ax_re_deployment 扩展表记录操作人信息
        extAxReProcDefService.create(definition.getId(), operatorAssigner);

    }
}
