package cn.fateverse.workflow.process.listener;

import cn.fateverse.workflow.constant.ProcessConstant;
import cn.fateverse.workflow.enums.OperationStateEnums;
import cn.fateverse.workflow.mapper.UserInstanceMapper;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * task任务创建监听器
 *
 * @author Clay
 * @date 2022/12/29
 */
@Component
public class TaskCreatedListener implements TaskListener {

    private final TaskService taskService;

    private final RuntimeService runtimeService;

    private final UserInstanceMapper userInstanceMapper;

    public TaskCreatedListener(TaskService taskService,
                               RuntimeService runtimeService, UserInstanceMapper userInstanceMapper) {
        this.taskService = taskService;
        this.runtimeService = runtimeService;
        this.userInstanceMapper = userInstanceMapper;
    }

    @Override
    public void notify(DelegateTask delegateTask) {
        //判断当前的task是否是自动通过
        if (OperationStateEnums.AUTO_REFUSE.getState().equals(delegateTask.getAssignee())) {
            Object autoRefuse = delegateTask.getVariable(OperationStateEnums.AUTO_REFUSE.getState());
            if (null == autoRefuse) {
                taskService.complete(delegateTask.getId());
            } else {
                changVariables(delegateTask, ProcessConstant.BUSINESS_STATUS_REJECT);
                runtimeService.deleteProcessInstance(delegateTask.getProcessInstanceId(), "审批人为空,自动驳回");
                userInstanceMapper.updateState(delegateTask.getProcessInstanceId(), ProcessConstant.BUSINESS_STATUS_REJECT);
            }
        }
    }

    /**
     * 改变运行装填
     *
     * @param delegateTask 执行器任务信息
     * @param state     需要修改的状态
     */
    private void changVariables(DelegateTask delegateTask, String state) {
        //获取流程数据,并设置为拒绝状态
        Map<String, Object> variables = delegateTask.getTransientVariables();
        variables.put(ProcessConstant.PROCESS_STATUS, state);
        //将表单数据设置到流程中
        runtimeService.setVariables(delegateTask.getProcessInstanceId(), variables);
    }
}
