package com.leanwo.activiti.listener.base;

import java.util.Date;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;

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

/**
 * 单据状态任务监听器，设置在结束事件上
 * 
 * @author YangZhiJie
 *
 */
public class DocumentStatusExecutionListener implements ExecutionListener {
	
	@Override
	public void notify(DelegateExecution execution) {
		String command = (String) execution.getVariable(UserPreference.COMMAND);

		Long recordId = (Long) execution.getVariable(UserPreference.RECORD_ID);
		Long accountId = (Long) execution.getVariable(UserPreference.ACCOUNT_ID);
		String className = (String) execution.getVariable(UserPreference.CLASS_NAME);

		DocumentInfoDto documentInfoDto = new DocumentInfoDto();
		documentInfoDto.setRecordId(recordId);
		documentInfoDto.setClassName(className);

		DocumentOperationService documentOperationService = (DocumentOperationService) SpringUtil
				.getSingleBean(DocumentOperationService.class);
		if (command != null && command.equals(TaskCommand.REJECT.toString())) {
			documentOperationService.rejectDocument(accountId, documentInfoDto);
		} else if (command != null && command.equals(TaskCommand.APPROVE.toString())) {
			documentOperationService.approveDocument(accountId, documentInfoDto);
		} else if (command != null && command.equals(TaskCommand.WITHDRAW.toString())) {
			documentOperationService.withdrawDocument(accountId, documentInfoDto);
		}

		execution.setVariable(UserPreference.PROCESS_INSTANCE_END_DATE, new Date());
	}

}
