package org.springblade.flow.base.util;

import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springblade.flow.engine.custom.constants.BasicActivitiConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author LoveMyOrange
 * @create 2022-01-06 14:13
 */
@Component
public class ActivitiDataBaseUtils {

    @Resource
    private HistoryService historyService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private TaskService taskService;
    @Resource
    private ManagementService managementService;

    /**
     * 获取流程发起人的方法
      * @param processInstanceId
     * @return
     */
   public String getApplyUserIdVariable(String processInstanceId){
       HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).variableName(BasicActivitiConstants.startEventInitiator).singleResult();
       return historicVariableInstance.getValue().toString();
   }

    /**
     * 通过流程实例id 和 任务节点key  可能会取到多个任务  然后get到第一个
     * 实际上这种获取是不准的,但是没办法
     * @return
     */
   public Task getTaskByProcessInstanceIdAndTaskDefinitionKey(String processInstanceId,String taskDefinitionKey){
       Task task = taskService.createNativeTaskQuery().sql("SELECT ASSIGNEE_  FROM " +
               managementService.getTableName(TaskEntity.class) + " WHERE PROC_INST_ID_ = #{processInstanceId} AND TASK_DEF_KEY_ = #{taskDefinitionKey}")
               .parameter("processInstanceId", processInstanceId)
               .parameter("taskDefinitionKey", taskDefinitionKey)
               .list().get(0);
       return task;
   }
}
