package com.hotent.portal.jms.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.hutool.json.JSONUtil;
import com.hotent.base.jms.JmsHandler;
import com.hotent.base.jms.JmsMessage;
import com.hotent.portal.model.SysMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import com.hotent.base.jms.JmsActor;
import com.hotent.base.jms.NoticeMessageType;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.StringUtil;
import com.hotent.base.vo.ClientInfo;

import com.hotent.portal.model.AppPushContent;
import com.hotent.portal.model.MsgTemplate;
import com.hotent.portal.model.SysExecutor;
import com.hotent.portal.persistence.manager.MessageLogManager;
import com.hotent.portal.persistence.manager.MsgTemplateManager;
import com.hotent.portal.persistence.manager.SysMessageManager;
import com.hotent.portal.service.impl.TemplateServiceImpl;

/**
 * 内部消息处理器
 *
 * @company 广州宏天软件股份有限公司
 * @author heyifan
 * @email heyf@jee-soft.cn
 * @date 2018年10月9日
 */
@Service
public class InnerHandler implements JmsHandler {
	private static final Logger logger = LoggerFactory.getLogger(InnerHandler.class);
	@Resource
	SysMessageManager sysMessageManager;
	@Resource
	MessageLogManager messageLogManager;

	@Resource
	AppPushHandler appPushHandler;
	@Resource
	MsgTemplateManager msgTemplateManager;
	@Resource
	TemplateServiceImpl templateServiceImpl;

	@Override
	public String getType() {
		return NoticeMessageType.INNER.key();
	}

	@Override
	public boolean send(JmsMessage jmsMessage) {
		try {
			//处理消息
			List<JmsActor> receivers = jmsMessage.getReceivers();
			//构造接收人
			List<SysExecutor> list = new ArrayList<SysExecutor>();
			for(JmsActor actor : receivers){
				SysExecutor executor = new SysExecutor(actor.getId(), actor.getName(), SysExecutor.TYPE_USER);
				list.add(executor);
			}
			if(BeanUtils.isEmpty(list)) {
				return false;
			}

			String senderId = null;
			String senderName = null;
			JmsActor sender = jmsMessage.getSender();
			if(BeanUtils.isNotEmpty(sender)) {
				senderId = sender.getId();
				senderName = sender.getName();
			}

			System.out.println("================================================jmsMessage");
			System.out.println(JSONUtil.parse(jmsMessage).toString());
			String ownerSource = SysMessage.OWNER_SOURCE_PLATFORM;
			String ownerSourceId = "-1";
			Map<String, Object> map = jmsMessage.getExtendVars();
			String processDefId = (String) map.get("processDefId_");
			if(StringUtil.isNotEmpty(processDefId)) {
				ownerSource = SysMessage.OWNER_SOURCE_FLOW;
				ownerSourceId = processDefId;
			}
			sysMessageManager.sendMsg(jmsMessage.getSubject(), jmsMessage.getContent(), jmsMessage.getType(), senderId, senderName, list,
					ownerSource, ownerSourceId);

            // 推送手机app消息
            String content =jmsMessage.getContent();
            if (StringUtil.isNotEmpty(jmsMessage.getTemplateAlias())) {
            	  MsgTemplate msgTemplate = msgTemplateManager.getByKey(jmsMessage.getTemplateAlias());
                  if(BeanUtils.isNotEmpty(msgTemplate)){
                  	jmsMessage.getExtendVars().put("templateType", msgTemplate.getTypeKey());
                  }
            	templateServiceImpl.parsePlainContent(msgTemplate, jmsMessage.getExtendVars());
			}
            Map<String,Object> vars = jmsMessage.getExtendVars();
			Map<String,Object> params = new HashMap<>();
			params.put("taskId", vars.getOrDefault("taskId", ""));
			params.put("instId", vars.getOrDefault("instId", ""));
			params.put("templateType", vars.getOrDefault("templateType",""));
			params.put("templateAlias", jmsMessage.getTemplateAlias());
			for (JmsActor actor : receivers) {
				if(BeanUtils.isNotEmpty(actor.getClientId())){
					appPushHandler.pushIndexMsgToSingle(new ClientInfo(actor.getClientId(),actor.getClientToken()),
							new AppPushContent(jmsMessage.getSubject(), content, params));
				}
			}

			messageLogManager.handLogByMsgHander(jmsMessage, true, "");
			return true;
		}
		catch(Exception ex) {
			logger.error(ex.getMessage());
			messageLogManager.handLogByMsgHander(jmsMessage, false, ex.getMessage());
			return false;
		}
	}

	@Override
	public String getTitle() {
		return "内部消息";
	}

	@Override
	public boolean getIsDefault() {
		return true;
	}

	@Override
	public boolean getSupportHtml() {
		return false;
	}
}
