package com.leanwo.activiti.listener.base;

import java.util.List;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.runtime.Execution;

import com.leanwo.activiti.dto.base.TaskCommand;
import com.leanwo.activiti.service.base.impl.UserPreference;
import com.leanwo.activiti.util.SpringUtil;

/**
 * 用户任务被拒绝/被撤销修改的监听器
 * @author YangZhiJie
 *
 */
public class UserTaskStopListener implements TaskListener {

	@Override
	public void notify(DelegateTask delegateTask) {
		
		String command = (String) delegateTask.getVariable(UserPreference.COMMAND);
		
		if(command != null && (command.equals(TaskCommand.REJECT.toString()) || command.equals(TaskCommand.WITHDRAW.toString()))){
			
			String processInstanceId = delegateTask.getProcessInstanceId();
			
			RuntimeService runtimeService = (RuntimeService) SpringUtil.getSingleBean(RuntimeService.class);
			
			List<Execution> executions = runtimeService.createExecutionQuery().messageEventSubscriptionName(UserPreference.STOP_MESSAGE).processInstanceId(processInstanceId).list();
			
			if(executions != null && executions.size() > 0) {
				for(int i = 0; i < executions.size(); i ++) {
					Execution execution = executions.get(i);
					runtimeService.messageEventReceived(UserPreference.STOP_MESSAGE, execution.getId());
				}
			}
		}
	}

}
