package com.uas.platform.b2b.support;

import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Service
public class SendMailService {
	
	@Autowired
	private JavaMailSenderImpl mailSender;
	@Autowired
	private SimpleMailMessage simpleMailMessage;
	@Autowired
	private VelocityEngine velocityEngine;

	private final static Logger LOGGER = Logger.getLogger(SendMailService.class);

	/**
	 * 发送模板邮件
	 * 
	 * @param to
	 *            接收邮件地址
	 * @param subject
	 *            主题
	 * @param model
	 *            传入模板的参数
	 * @param tplLocation
	 *            模板路径
	 */
	public void sendTemplateMail(String to, String subject, Map<String, Object> model, String tplLocation) {
		String result = null;
		try {
			result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, tplLocation, "UTF-8", model);
		} catch (Exception e) {
			LOGGER.info("merge template " + tplLocation + " into string occur error, can not send mail to " + to);
		}
		sendHtmlMail(to, subject, result);
	}

	/**
	 * 发送普通html邮件 <strong>统一使用UTF-8格式</strong>
	 * 
	 * @param to
	 *            接收邮件地址
	 * @param subject
	 *            主题
	 * @param content
	 *            邮件内容
	 */
	public void sendHtmlMail(String to, String subject, String content) {
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			messageHelper.setTo(to);
			messageHelper.setFrom(simpleMailMessage.getFrom());
			messageHelper.setSubject(subject);
			messageHelper.setText(content, true);
		} catch (MessagingException e) {
			LOGGER.info("html text error, can not send mail to " + to);
		}
		mailSender.send(mimeMessage);
	}
	
}
