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

import cn.axzo.workflow.core.engine.event.ExtTaskInstCreateEvent;
import cn.axzo.workflow.core.engine.event.ExtTaskInstUpdateEvent;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.ReceiveTask;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.behavior.ReceiveTaskActivityBehavior;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.TaskHelper;
import org.flowable.task.api.Task;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.Objects;

import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.APPROVED;
import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.PROCESSING;

/**
 * 自定义 ReceiveTask 行为
 *
 * @author wangli
 * @since 2023/11/23 14:41
 */
@Slf4j
public class CustomReceiveTaskActivityBehavior extends ReceiveTaskActivityBehavior {
    protected ReceiveTask receiveTask;
    protected ExtAxHiTaskInstService hiTaskInstService;

    public CustomReceiveTaskActivityBehavior(ReceiveTask receiveTask, ExtAxHiTaskInstService hiTaskInstService) {
        this.receiveTask = receiveTask;
        this.hiTaskInstService = hiTaskInstService;
    }

    @Override
    public void execute(DelegateExecution execution) {
        super.execute(execution);
        // 记录task表, 可被审批记录检索到
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        TaskService taskService = processEngineConfiguration.getTaskServiceConfiguration().getTaskService();
        TaskEntity task = taskService.createTask();
        task.setExecutionId(execution.getId());
        task.setTaskDefinitionKey(receiveTask.getId());
        task.setPropagatedStageInstanceId(execution.getPropagatedStageInstanceId());
        task.setName(receiveTask.getName());
        TaskHelper.insertTask(task, (ExecutionEntity) execution, false, false);

        // 添加 taskInst 扩展表数据
        FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
        eventDispatcher.dispatchEvent(new ExtTaskInstCreateEvent(execution.getProcessInstanceId(),
                        execution.getCurrentActivityId(), task.getId(), PROCESSING),
                processEngineConfiguration.getEngineCfgKey());
    }

    @Override
    public void leave(DelegateExecution execution) {
        CommandContext commandContext = CommandContextUtil.getCommandContext();
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();

        org.flowable.engine.TaskService taskService = processEngineConfiguration.getTaskService();
        Task task = taskService.createTaskQuery().executionId(execution.getId())
                .taskDefinitionKey(execution.getCurrentActivityId()).singleResult();
        if (Objects.nonNull(task)) {
            eventDispatcher.dispatchEvent(new ExtTaskInstUpdateEvent(execution.getProcessInstanceId(),
                            receiveTask.getId(), task.getId(), APPROVED),
                    processEngineConfiguration.getEngineCfgKey());
        } else {
            log.warn("task is null, executionId: {}, activityId: {}", execution.getId(),
                    execution.getCurrentActivityId());
        }
        super.leave(execution);
    }
}
