package cn.axzo.workflow.core.service.impl;

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnActivitySetAssigneeDTO;
import cn.axzo.workflow.core.common.exception.WorkflowEngineException;
import cn.axzo.workflow.core.engine.cmd.CustomBizSpecifyAssigneeToTaskCmd;
import cn.axzo.workflow.core.service.BpmnProcessActivityService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.stereotype.Service;

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

import static cn.axzo.workflow.core.common.code.BpmnTaskRespCode.ACTIVITY_TRIGGER_NOT_EXISTS;


@Service
@Slf4j
public class BpmnProcessActivityServiceImpl implements BpmnProcessActivityService {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private SpringProcessEngineConfiguration processEngineConfiguration;

    @Override
    public void trigger(String executionId) {
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        if (Objects.isNull(execution)) {
            throw new WorkflowEngineException(ACTIVITY_TRIGGER_NOT_EXISTS, executionId);
        }
        runtimeService.trigger(executionId);
    }

    @Override
    public void setAssignee(BpmnActivitySetAssigneeDTO dto) {
        CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
        commandExecutor.execute(new CustomBizSpecifyAssigneeToTaskCmd(dto.getTriggerId(), dto.getAssigners()));
    }
}
