package com.blueland.bpm.unitework;

import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blueland.bpm.engine.core.model.ExceptionErrorCode;
import com.blueland.bpm.engine.core.model.ProcessInstanceModel;
import com.blueland.bpm.engine.core.model.ProcessMgrDataShare;
import com.blueland.bpm.engine.core.model.TaskEntityDataShare;
import com.blueland.bpm.engine.util.WorkFlowContants;
import com.blueland.bpm.engine.util.WorkFlowException;
import com.blueland.unitework.model.UniteworkTask;
import com.blueland.unitework.service.UniteworkService;

/**
 * 统一待办消息同步监听类-任务删除（待办变已办）
 * 
 * @version: 1.0
 * @author lw
 */
public class TaskDeleleEvent extends TaskCommonEvent {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void onDelete(ActivitiEvent event) {
		if (!(ActivitiEventType.ENTITY_DELETED.equals(event.getType()) && ((ActivitiEntityEvent) event)
				.getEntity() instanceof TaskEntity)) {
			return;
		}
		try {
			TaskEntity delegateTask = (TaskEntity) ((ActivitiEntityEvent) event)
					.getEntity();
			HistoricTaskInstanceEntity histask=Context.getCommandContext().getHistoricTaskInstanceEntityManager().findHistoricTaskInstanceById(delegateTask.getId());
			UniteworkService uniteworkService = (UniteworkService) com.blueland.bpm.common.util.ApplicationContextHolder
					.getBean("uniteworkService");
			ProcessInstanceModel processInfo = buildProcessInstanceModel(delegateTask);
			boolean isSendESB=isSendESB(delegateTask);
			UniteworkTask his=uniteworkService.changeToYiban(getZaibanId(processInfo),isSendESB?histask.getEndTime():delegateTask.getCreateTime());
			if(isSendESB){
				TaskEntityDataShare.setHisTask(his);
			}
		} catch (Exception e) {
			/**
			 * 当流程管理中删除流程定义时,统一待办库可能存在异常,如找不到待办ID等等
			 * 为了不影响删除逻辑此处不抛出异常(通过前端在ProcessMgrDataShare中设置PROCESS_DEF_DEL_MANAGE_OPT标识来判断)
			 * ProcessMgrDataShare.setProcessMgrData(PROCESS_DEF_DEL_MANAGE_OPT)在ProcessDefinitionController.delete()方法中
			 */
			Object obj=ProcessMgrDataShare.getProcessMgrData();
			if(obj!=null&&WorkFlowContants.PROCESS_DEF_DEL_MANAGE_OPT.equals(obj)){
				return;
			}
			throw new WorkFlowException(ExceptionErrorCode.C3002,"消息类型[待办变已办],同步统一待办消息失败", e);
		}
	}

	@Override
	public boolean isFailOnException() {
		// The logic in the onEvent method of this listener is not critical,
		// exceptions
		// can be ignored if logging fails...
		return true;
	}

}