package com.blueland.bpm.engine.core.listener;

import java.util.Date;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blueland.bpm.common.util.ApplicationContextHolder;
import com.blueland.bpm.engine.config.model.ActivityInfoConfig;
import com.blueland.bpm.engine.core.model.ExceptionErrorCode;
import com.blueland.bpm.engine.core.model.ProcessInputModel;
import com.blueland.bpm.engine.core.service.ProcessConfigService;
import com.blueland.bpm.engine.util.ProcessDefinitionUtils;
import com.blueland.bpm.engine.util.WorkFlowException;

/**
 * 全局的任务过期时间处理监听器
 * @version:  1.0
 * @author lw 
 */
public class GlobalTaskDutDateListener implements TaskListener {
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void notify(DelegateTask delegate) {
		if (!delegate.getEventName().equals(TaskListener.EVENTNAME_CREATE))
			return;
		TaskEntity delegateTask = (TaskEntity) delegate;
		logger.debug("触发了全局监听器, pid={}, tid={}, event={}", new Object[] {
				delegateTask.getProcessInstanceId(), delegateTask.getId(),
				delegateTask.getEventName() });
		
		Date limitTime = null;
		try {
			ProcessInputModel processInputModel = ProcessDefinitionUtils
					.getWfprocessInputModel(delegateTask);
			int limit = processInputModel.getWf_actLimitTime();
			if(limit >0 ) {
				limitTime = DateUtils.addDays(new Date(), limit);
				delegateTask.setLimitTime(limit);
			}else {
				ProcessConfigService processConfigService = (ProcessConfigService) ApplicationContextHolder
						.getBean("processConfigServiceImpl");
				ActivityInfoConfig activityInfoConfig = processConfigService
						.getActivityInfoConfig(delegate.getProcessDefinitionId(),
						delegate.getTaskDefinitionKey());
				if (activityInfoConfig != null
						&& activityInfoConfig.getActivityLimitTime() != null
						&& activityInfoConfig.getActivityLimitTime() > 0) {
					delegateTask.setDueDate(DateUtils.addDays(new Date(),
							activityInfoConfig.getActivityLimitTime()));
					delegateTask.setLimitTime(activityInfoConfig.getActivityLimitTime());
				}
			}
		} catch (Exception e) {
			throw new WorkFlowException(ExceptionErrorCode.B2050,"setDueDate error,delegate:"
					+ delegate, e);
		}
	}
}