package com.codvision.workflow.listener.task;


import com.codvision.commoncore.exception.BusinessException;
import com.codvision.workflow.entity.WorkFlowRecord;
import com.codvision.workflow.service.WorkFlowRecordService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

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


/**
 * 自定义操作次数限制监听器（任务监听器 事件类型 -> complete）
 * @author hxl
 */
@RequiredArgsConstructor
@Component(value = "workFlowCustomOperateLimitListener")
public class WorkFlowCustomOperateLimitListener {

    private final TaskService taskService;
    private final WorkFlowRecordService workFlowRecordService;

    /**
     * 执行方法
     * @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;
        }

        WorkFlowRecord workFlowRecord = workFlowRecordService.getByTaskId(delegateTask.getId());
        if (workFlowRecord == null) {
            return;
        }

        int limitTarget = limitType == 0 ? workFlowRecord.getOperatorUid() : workFlowRecord.getOperatorOid();
        String key = TASK_OPERATE_LIMIT + delegateTask.getTaskDefinitionKey() + "_" + limitType + "_" + limitTarget;
        Integer count = (Integer) taskService.getVariable(delegateTask.getId(), key);
        count = count == null ? 1 : ++count;
        if (count > limitCount) {
            throw new BusinessException("分配次数已达上限");
        }

        taskService.setVariable(delegateTask.getId(), key, count);
    }
}
