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

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blueland.bpm.engine.core.handler.GlobalBizHandler;
import com.blueland.bpm.engine.util.SmsUtil;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.User;
import com.blueland.unitework.model.UniteworkTask;
import com.blueland.unitework.service.MsgService;
import com.blueland.unitework.service.UniteworkService;

public class GlobalTaskMsgMotice implements GlobalBizHandler{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	UniteworkService uniteworkService = (UniteworkService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("uniteworkService");
	MsgService imService = (MsgService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("imService");
	UserService userService = (UserService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("userServiceImpl");
	
	
	
	@Override
	public void execute(Map<String,Object> processMap) {
		// TODO Auto-generated method stub
		exeTasks(processMap);
		exeHisTasks(processMap);
	}
	
	/**
	 * 待办通知
	 * @param processMap
	 */
	private void exeTasks(Map<String,Object> processMap){
		List<UniteworkTask> tasks=(List<UniteworkTask>) processMap.get(GlobalTaskMsgMotice.TASKS_KEY);
		if(tasks==null||tasks.isEmpty()){
			return;
		}
		for (UniteworkTask task : tasks) {
			try{
				noticeTask(task);
			}catch(Exception e){
				logger.error(String.format("待办提醒消息发送失败,task[%s],processMap[%s]",task,processMap));
			}
		}
	}
	
	/**
	 * 已办通知
	 * @param processMap
	 */
	private void exeHisTasks(Map<String,Object> processMap){
		List<UniteworkTask> hisTasks=(List<UniteworkTask>) processMap.get(GlobalTaskMsgMotice.HIS_TASKS_KEY);
		if(hisTasks==null||hisTasks.isEmpty()){
			return;
		}
		for (UniteworkTask hisTask : hisTasks) {
			try{
				noticeHisTask(hisTask);
			}catch(Exception e){
				logger.error(String.format("已办提醒消息发送失败,task[%s],processMap[%s]",hisTask,processMap));
			}
		}
	}
	
	
	private void noticeTask(UniteworkTask task){
		String msgId = imService.sendTodoMsg(task);
		if(!StringUtils.isEmpty(msgId)){
			task.setMessageId(msgId);
		}
		uniteworkService.updateMsgId(task);
		try {
			User user=userService.getUserById(task.getRecUserId());
			String context="湖南中烟信息集成平台提醒您，您有一条待办消息.\\n消息标题:"+task.getTitle();
			String resultSms=SmsUtil.sendSms(context,user.getUserMobile(), task.getSendUserId(), "ebpm");
			logger.info("待办短信提醒结果："+resultSms);
		}catch(Exception e) {
			logger.error("待办短信提醒出现异常，UniteworkTask："+task,e);
		}
	}
	
	
	private void noticeHisTask(UniteworkTask task) {
		imService.sendUptMsg(task, "已处理待办："+ task.getTitle());
	}
}
