/**
 * 
 */
package org.springblade.message.email;

import java.util.Collection;
import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springblade.message.MsgTemplate;
import org.springblade.message.model.EmailInfo;
import org.springblade.message.model.EmailMsgRequest;
import org.springblade.message.model.MsgResponse;
import org.springframework.stereotype.Component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class EmailMsgTemplate implements MsgTemplate {

	//设置超时时间
	final static int TIME_OUT = 5000;

	@Override
	public MsgResponse sendEmailMessage(EmailMsgRequest emailMsgRequest) {
		try {
			if (emailMsgRequest == null || emailMsgRequest.getEmailInfo() == null
					|| CollectionUtil.isEmpty(emailMsgRequest.getEmails())) {
				return MsgResponse.failure("收件人邮箱不能为空");
			}
			EmailInfo emailInfo = emailMsgRequest.getEmailInfo();
			String username = emailInfo.getUserName();
			String password = emailInfo.getPassWord();
			String smtp = emailInfo.getSmtpHost();
			
			if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password) || StrUtil.isEmpty(smtp)) {
				return MsgResponse.failure("核心参数不能为空");
			}

			// 1. 创建参数配置, 用于连接邮件服务器的参数配置
			Properties props = new Properties();
			// 使用的协议（JavaMail规范要求）
			props.setProperty("mail.transport.protocol", "smtp");
			// 发件人的邮箱的 SMTP 服务器地址
			props.setProperty("mail.smtp.host", smtp);
			// 需要请求认证
			props.setProperty("mail.smtp.auth", "true");
			props.put("mail.smtp.port", emailInfo.getSmtpPort());
			props.put("mail.smtp.timeout", TIME_OUT);
			props.put("mail.smtp.connectiontimeout", TIME_OUT);
			props.put("mail.smtp.writetimeout", TIME_OUT);
			props.put("mail.smtp.socketFactory.port", emailInfo.getSocketFactoryPort());
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", false);

			// 2. 根据配置创建会话对象, 用于和邮件服务器交互
			Session session = Session.getInstance(props);
			// 设置为debug模式, 可以查看详细的发送 log
			session.setDebug(false);
			// 3. 创建一封邮件 session、发件人、收件人、邮件内容,主题
			MimeMessage message = createMimeMessage(session, emailMsgRequest);
			// 4. 根据 Session 获取邮件传输对象
			Transport transport = session.getTransport();

			// 5. 使用 邮箱账号 和 密码/授权码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
			transport.connect(username, password);

			// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人,
			// 密送人
			transport.sendMessage(message, message.getAllRecipients());
			// 7. 关闭连接
			transport.close();
			log.info("邮件发送成功，接收邮箱为：" + String.join(",", emailMsgRequest.getEmails()));
			return MsgResponse.success(200, "邮件发送成功");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return MsgResponse.failure("邮件发送失败");
		}
	}

	/**
	 * 创建邮件
	 *
	 * @param session
	 * @param myEmailAccount
	 * @param receiveMailAccount
	 * @return
	 * @throws Exception 
	 */
	private MimeMessage createMimeMessage(Session session, EmailMsgRequest emailMsgRequest) throws Exception {
		try {
			EmailInfo emailInfo = emailMsgRequest.getEmailInfo();
			Collection<String> emails = emailMsgRequest.getEmails();

			// 1. 创建一封邮件
			MimeMessage mimeMessage = new MimeMessage(session);
			// 2. From: 发件人 emailUserName、昵称、编码格式
			mimeMessage.setFrom(new InternetAddress(emailInfo.getUserName(),
					"几何BI" + "<" + emailInfo.getUserName() + ">", "UTF-8"));

			// 3. To: 收件人（可以增加多个收件人）
//			mimeMessage.setRecipient(MimeMessage.RecipientType.TO,
//					new InternetAddress(receiveMailAccount, "收件人名称", "UTF-8"));
			// 多个收件人
			for (String email : emails) {
				mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
			}

			// 4. Subject: 邮件主题
			mimeMessage.setSubject(emailMsgRequest.getTitle(), "UTF-8");
			// 5. Content: 邮件正文（可以使用html标签）
			mimeMessage.setContent(emailMsgRequest.getBody(), "text/html;charset=UTF-8");
			// 6. 设置发件时间
			mimeMessage.setSentDate(new Date());

			// 7. 保存设置
			mimeMessage.saveChanges();
			return mimeMessage;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
	}
}
