package com.codvision.workflow.listener.task;

import com.codvision.workflow.service.WorkFlowService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.springframework.stereotype.Component;

import java.util.List;

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


/**
 * 自动办结
 * @author hxl
 */
@RequiredArgsConstructor
@Component(value = "workFlowAutoCompleteListener")
public class WorkFlowAutoCompleteListener implements TaskListener {

    private final WorkFlowService workFlowService;
    private final TaskService taskService;


    /**
     * 若当前节点无办理人（含候选人与候选组），则自动办结（事件类型 -> create）
     * @param delegateTask 当前节点
     */
    @Override
    public void notify(DelegateTask delegateTask) {
        List<Integer> userIds = workFlowService.getTaskRelatedUserIds(delegateTask.getId());
        if (CollectionUtils.isNotEmpty(userIds)) {
            return;
        }

        taskService.setVariableLocal(delegateTask.getId(), AUTO_COMPLETE_NO_USERS, true);
        taskService.complete(delegateTask.getId());
    }
}
