package cn.component.message.sms;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSONObject;

import cn.constant.SendMsgStatusEnum;
import cn.orm.abs.ISqlToyDao;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.pojo.entity.TSysSms;
import cn.pojo.entity.TSysSmsTemplate;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.time.TimeKit;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 消息生成工具
 */
@Component
public class PushMsgUtil {

	@Autowired
	private ISqlToyDao daoService;
	
	@Autowired
	private Configuration freemarkerConfig;
	/**
	 * @param msgType 消息类型 1短信 2邮件 3微信
	 * @param templateCode    消息模板码
	 * @param map     消息参数
	 * @param sentTo  接收消息方
	 */
	public boolean sendMessage(String msgType, String templateCode, Map<String, String> map, String sentTo)
	{
		QueryWrapper<TSysSmsTemplate> queryWrapper = Wrappers.wrapper(TSysSmsTemplate.class)
				.eq("templateCode", templateCode);
		TSysSmsTemplate sysSmsTemplate = daoService.findOne(queryWrapper);
		
		TSysSms sysMessage = new TSysSms();
		if(IsKit.isNullOrEmpty(sysSmsTemplate))
		{
			sysMessage.setEsType(msgType);
			sysMessage.setEsReceiver(sentTo);
			//模板标题
			String title = sysSmsTemplate.getTemplateName();
			//模板内容
			String content = sysSmsTemplate.getTemplateContent();
			StringWriter stringWriter = new StringWriter();
			Template template = null;
			try {
				template = new Template("SysMessageTemplate", content, freemarkerConfig);
				template.process(map, stringWriter);
			} catch (IOException e) {
				LogKit.info(e.getMessage());
				return false;
			} catch (TemplateException e) {
				LogKit.info(e.getMessage());
				return false;
			}
			content = stringWriter.toString();
			sysMessage.setEsTitle(title);
			sysMessage.setEsContent(content);
			sysMessage.setEsParam(JSONObject.toJSONString(map));
			sysMessage.setEsSendTime(TimeKit.getNowLocalDateTime());
			sysMessage.setEsSendStatus(SendMsgStatusEnum.WAIT.getCode());
			sysMessage.setEsSendNum(0);
			if(IsKit.isNotNull(daoService.save(sysMessage))) {
				return true;
			}
		}
		return false;
	}
}
