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

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueland.bpm.engine.core.handler.GlobalBizHandler;
import com.blueland.bpm.engine.core.handler.GlobalBizHandlerFactory;
import com.blueland.bpm.engine.core.handler.GlobalBizHandlerInterceptor;
import com.blueland.bpm.engine.core.handler.GlobalBizHandlerInvocation;
import com.blueland.bpm.engine.core.model.ProcessInputModel;
import com.blueland.bpm.engine.core.model.ProcessInstanceModel;
import com.blueland.bpm.engine.core.model.TaskEntityDataShare;
/**
 * 流程执行Service
 * @version:  1.0
 * @author lw 
 */
@Service
public class ProcessExecuteServiceFacde {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	ProcessExecuteService processExecuteService;
	public static String  EXECUTE_STATUS_SUCCESS="SUCCESS";
	public static String  EXECUTE_STATUS_ERROR="ERROR";

	/**
	 * 流程执行接口
	 * 
	 * @param processInputModel
	 * @return Map<String,Object>
	 */
	public Map<String, Object> nextExecute(ProcessInputModel processInputModel) {
		TaskEntityDataShare.clear();
		Map<String, Object> result = processExecuteService
				.nextExecute(processInputModel);
		String executeStatus = (String) result.get("executeStatus");
		if (executeStatus == EXECUTE_STATUS_ERROR) {
			return result;
		}
		ProcessInstanceModel processInstanceModel = (ProcessInstanceModel) result
				.get("processInstanceModel");
		//加入待办/已办列表
		result.put("tasks", TaskEntityDataShare.getTask());
		result.put("hisTasks", TaskEntityDataShare.getHisTask());
		try {
			if (processInstanceModel != null) {
				notifyByThread(result, processInstanceModel);
			}
		} catch (Exception e) {
			logger.error("",e);
		} finally {
			TaskEntityDataShare.clear();
		}
		return result;
	}
	
	
	/**
	 * 流程执行后通知处理器
	 * @param processInstanceModel
	 */
	private void notifyByThread(final Map<String, Object> resultMap,final ProcessInstanceModel processInstanceModel) {
		ExecutorService pool = Executors.newCachedThreadPool();
		pool.execute(new Runnable() {
			public void run() {
				notifyTask(resultMap,processInstanceModel);
			}
		});
		pool.shutdown();
		try {
			while (!pool.awaitTermination(1, TimeUnit.HOURS)) {
				logger.info("notifyByThread还没有关闭");
			}
		} catch (InterruptedException e) {
			logger.error("",e);
		}
		
	}
	
	/**
	 * 流程执行后通知处理器
	 * @param processInstanceModel
	 */
	private void notifyTask(Map<String, Object> resultMap,ProcessInstanceModel processInstanceModel) {
		GlobalBizHandlerInterceptor interceptor = new GlobalBizHandlerInterceptor();
		List<GlobalBizHandler> globalProcessHandlerServices = GlobalBizHandlerFactory.getInstance()
				.getGlobalProcessHandlerService(GlobalBizHandler.AGENT_TYPE_AFTER);
		if (globalProcessHandlerServices == null
				|| globalProcessHandlerServices.isEmpty())
			return;
		for (GlobalBizHandler globalProcessHandlerService : globalProcessHandlerServices) {
			
			try {
				interceptor
						.handleInvocation(new GlobalBizHandlerInvocation(
								globalProcessHandlerService,resultMap));

			} catch (Exception e) {
				String errorMsg=String.format("标题为[%s]的流程调用全局业务代理[%s]出现异常,processInputModel对象数据为[%s]",processInstanceModel.getProcTitle(),globalProcessHandlerService,processInstanceModel);
				//processErrorLogManager.save(new ProcessErrorLog(processInputModel.getWf_procInstId(),processInputModel.getWf_procTitle(),processInputModel.getWf_sender(),processInputModel.getWf_actionType(),errorMsg,jsonMsg));
				logger.error(errorMsg, e);
			}
		}
	}
	

	
}
