package com.blueland.ebpm.listenner;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.engine.config.model.GloblBizProcessHandler;
import com.blueland.bpm.engine.config.service.GloblBizProcessHandlerManager;
import com.blueland.bpm.engine.core.handler.GlobalBizHandler;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.User;
import com.blueland.unitework.model.UniteworkTask;
import com.blueland.unitework.service.UniteworkService;
import com.rzdata.dzy.third.message.domain.AliyunSmsResult;
import com.rzdata.dzy.third.message.service.IMessageSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

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

/**
 * 待办提醒处理
 * 
 * @author lw
 *
 */

public class GlobalTaskMsgMotice implements GlobalBizHandler {

	private String TODOTYPE = "todo";
	protected Logger logger = LoggerFactory.getLogger(getClass());
	UniteworkService uniteworkService = (UniteworkService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("uniteworkService");
	UserService userService = (UserService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("userServiceImpl");
	ApplicationManager applicationManager = (ApplicationManager) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("applicationManager");

	IMessageSendService messageSendService = (IMessageSendService) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("messageSendServiceImpl");

	GloblBizProcessHandlerManager globlBizProcessHandlerManager = (GloblBizProcessHandlerManager) com.blueland.bpm.common.util.ApplicationContextHolder
			.getBean("globlBizProcessHandlerManager");

	@Value("${rzdata.sendSmsMessage}")
	String sendSmsMessage;

	@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) {
		try {
			GloblBizProcessHandler globlBizProcessHandler = globlBizProcessHandlerManager.getById("send_message");
			if(null == globlBizProcessHandler){
				return;
			}
			if(!"open".equals(globlBizProcessHandler.getGbphRemark())){
				return;
			}
			String msgTemplate = "您有一条待办消息。消息标题：{}";
			String userId = task.getRecUserId();
			User user = userService.getUserById(userId);
			if(null == user){
				return;
			}
			String msgContent = StrUtil.format(msgTemplate, task.getTitle());
			AliyunSmsResult aliyunSmsResult = messageSendService.sendSmsMessageSync(user.getUserMobile(), msgContent);
			System.out.println("短信发送结果====>" + "当前流程实例ID：" + task.getProcInstId() + "；当前环节实例ID：" + task.getCurActInstId()
					+ "；当前环节名称：" + task.getCurActDefName()  + "；发送结果：" + JSONUtil.toJsonStr(aliyunSmsResult));
		} catch (Exception e) {
			this.logger.error("发送消息错误：" + e);
		}

	}

	private void noticeHisTask(UniteworkTask task) {
		/*
		 * imService.sendUptMsg(task, "已处理待办："+ task.getTitle());
		 * mqService.putMsg(UniteworkService.buildDoneMsg(task), task);
		 */
	}
}
