package com.codvision.workflow.listener.task;

import com.codvision.workflow.entity.dto.WorkFlowTaskReturnLimitDTO;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.HashMap;

import static com.codvision.workflow.constant.WorkFlowConstant.TASK_RETURN_LIMIT;


/**
 * 回退次数限制监听器（任务监听器 事件类型 -> create）
 * @author hxl
 */
@RequiredArgsConstructor
@Component(value = "workFlowTaskReturnLimitListener")
public class WorkFlowTaskReturnLimitListener {

    private final TaskService taskService;

    /**
     * 执行方法
     * @param delegateTask 当前任务
     * @param limitType 限制类型 0-用户 1-组织
     * @param limitCount 限制次数
     * @param expression 布尔表达式
     */
    public void execute(DelegateTask delegateTask, Integer limitType, Integer limitCount, boolean expression) {
        if (!expression || limitType == null || limitCount == null) {
            return;
        }

        String variableName = TASK_RETURN_LIMIT + delegateTask.getTaskDefinitionKey();
        WorkFlowTaskReturnLimitDTO taskReturnLimit = (WorkFlowTaskReturnLimitDTO) taskService.getVariable(delegateTask.getId(), variableName);
        if (taskReturnLimit == null) {
            taskReturnLimit = WorkFlowTaskReturnLimitDTO.builder().taskDefinitionKey(delegateTask.getTaskDefinitionKey())
                    .limitType(limitType)
                    .limitCount(limitCount)
                    .userMap(new HashMap<>(16))
                    .orgMap(new HashMap<>(16))
                    .build();
            taskService.setVariable(delegateTask.getId(), variableName, taskReturnLimit);
        }
    }
}
