package com.wechat.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sun.mail.util.MailSSLSocketFactory;
import com.wechat.common.Constants;

@Component
public class MailUtil {
	protected static Logger logger = LoggerFactory.getLogger(MailUtil.class);

	@Value("#{configProperties['send_email_address']}")
	private String sendEmailAddress;
	
	@Value("#{configProperties['send_email_password']}")
	private String sendEmailPassword;
	/**
	 * 企业注册发送激活邮件
	 * 
	 * @param token
	 *            加密token
	 * @param userCode
	 * @param recipientAddress
	 * @return
	 */
	public  Boolean sendActivationMail(String token, String userCode, String recipientAddress) {
		Transport transport = null;
		Boolean flag = false;
		try {
			// 创建连接对象 连接到邮件服务器
			Properties properties = new Properties();
			// 设置用户的认证方式
			properties.setProperty("mail.smtp.auth", "true");

			// 设置传输协议
			properties.setProperty("mail.transport.protocol", "smtp");

			// 设置发件人的SMTP服务器地址
			properties.setProperty("mail.smtp.host", "smtp.mxhichina.com");
			// 开启ssl加密，如果没有ssl加密，会报530错误
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			// 2、创建定义整个应用程序所需的环境信息的 Session 对象
			Session session = Session.getInstance(properties);
			// 设置调试信息在控制台打印出来
			session.setDebug(false);
			// 3、创建邮件的实例对象
			Message msg = getMimeActivationMessage(session, sendEmailAddress, recipientAddress, token, userCode);
			// 4、根据session对象获取邮件传输对象Transport
			transport = session.getTransport();
			// 设置发件人的账户名和密码
			transport.connect(sendEmailAddress, sendEmailPassword);
			// 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
			transport.sendMessage(msg, msg.getAllRecipients());
			flag = true;
		} catch (NoSuchProviderException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (MessagingException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (Exception e) {
			flag = false;
			logger.error(e.getMessage());
		} finally {
			// 5、关闭邮件连接
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.error("企业注册邮件发送异常",e.getMessage());
				}

			}
		}
		return flag;
	}

	private static String domain = "";

	public static void setDomain(String domain) {
		MailUtil.domain = domain;
	}

	/**
	 * 
	 * @param session
	 * @param senderAddress
	 * @param recipientAddress
	 * @param token
	 * @param userCode
	 * @return
	 */
	private static MimeMessage getMimeActivationMessage(Session session, String senderAddress,
			String recipientAddress, String token, String userCode) {
		// 创建一封邮件的实例对象
		MimeMessage msg = null;
		try {
			msg = new MimeMessage(session);
			// 设置发件人地址
			msg.setFrom(new InternetAddress(senderAddress));
			/**
			 * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行 MimeMessage.RecipientType.TO:发送
			 * MimeMessage.RecipientType.CC：抄送 MimeMessage.RecipientType.BCC：密送
			 */
			msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
			// 设置邮件主题
			msg.setSubject("门墩儿验证", "UTF-8");
			// 设置邮件正文
			// msg.setText("验证码" + text);
			// msg.setContent("验证码" + text, "text/html;charset=UTF-8");

			StringBuffer sb = new StringBuffer("<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3>");
			sb.append("<a href=\"" + domain + "login/activation?userCode=");
			sb.append(userCode);
			sb.append("&activationToken=");
			sb.append(token);
			sb.append("\">点击链接激活");
			sb.append("</a>");
			sb.append("</h3></body></html>");
			/*
			 * String content =
			 * "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://192.168.1.118:8081/RecruitmentApi/login/activation?code="
			 * + token + "'&userCode='" + userCode + "'>点击激活</a></h3></body></html>";
			 */
			msg.setContent(sb.toString(), "text/html;charset=UTF-8");
			// 设置邮件的发送时间,默认立即发送
			msg.setSentDate(new Date());
		} catch (AddressException e) {
			logger.error("邮件发送异常",e.getMessage());
		} catch (MessagingException e) {
			logger.error("邮件发送异常",e.getMessage());
		}

		return msg;
	}

	/**
	 * 
	 * @param content 邮件内容
	 * @param recipientAddress 邮件地址
	 * @return
	 */
	public  Boolean sendCodeMail(String content, String recipientAddress) {
		Transport transport = null;
		Boolean flag = false;
		try {
			// 创建连接对象 连接到邮件服务器
			Properties properties = new Properties();
			// 设置用户的认证方式
			properties.setProperty("mail.smtp.auth", "true");

			// 设置传输协议
			properties.setProperty("mail.transport.protocol", "smtp");

			// 设置发件人的SMTP服务器地址
			properties.setProperty("mail.smtp.host", "smtp.mxhichina.com");
			// 开启ssl加密，如果没有ssl加密，会报530错误
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			// 2、创建定义整个应用程序所需的环境信息的 Session 对象
			Session session = Session.getInstance(properties);
			// 设置调试信息在控制台打印出来
			session.setDebug(true);
			// 3、创建邮件的实例对象
			Message msg = getMimeCodeMessage(session,sendEmailAddress, recipientAddress, content);
			// 4、根据session对象获取邮件传输对象Transport
			transport = session.getTransport();
			// 设置发件人的账户名和密码
			transport.connect(sendEmailAddress, sendEmailPassword);
			// 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
			transport.sendMessage(msg, msg.getAllRecipients());
			flag = true;
		} catch (NoSuchProviderException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (MessagingException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (Exception e) {
			flag = false;
			logger.error(e.getMessage());
		} finally {
			// 5、关闭邮件连接
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.error(e.getMessage());
				}

			}
		}
		return flag;
	}

	/**
	 * 
	 * @param session
	 * @param senderAddress
	 *            发件地址
	 * @param recipientAddress
	 *            收件地址
	 * @return
	 * @throws Exception
	 */
	private  MimeMessage getMimeCodeMessage(Session session, String senderAddress, String recipientAddress,
			String content) {
		// 创建一封邮件的实例对象
		MimeMessage msg = null;
		try {
			msg = new MimeMessage(session);
			// 设置发件人地址
			msg.setFrom(new InternetAddress(senderAddress));
			/**
			 * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行 MimeMessage.RecipientType.TO:发送
			 * MimeMessage.RecipientType.CC：抄送 MimeMessage.RecipientType.BCC：密送
			 */
			msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
			// 设置邮件主题
			msg.setSubject("门墩儿-酒店职业发展社交平台", "UTF-8");
			// 设置邮件正文
			//msg.setText("验证码" + code);
			msg.setContent(content, "text/html;charset=UTF-8");
			// 设置邮件的发送时间,默认立即发送
			msg.setSentDate(new Date());
		} catch (AddressException e) {
			logger.error("邮件验证码发送异常",e.getMessage());
		} catch (MessagingException e) {
			logger.error("邮件验证码发送异常",e.getMessage());
		}

		return msg;
	}
	public  Boolean sendMailNew(String recipientAddress, String mailContent,String subject) {
		Transport transport = null;
		Boolean flag = false;
		try {
			// 创建连接对象 连接到邮件服务器
			Properties properties = new Properties();
			// 设置用户的认证方式
			properties.setProperty("mail.smtp.auth", "true");

			// 设置传输协议
			properties.setProperty("mail.transport.protocol", "smtp");

			// 设置发件人的SMTP服务器地址
			properties.setProperty("mail.smtp.host", "smtp.mxhichina.com");
			// 开启ssl加密，如果没有ssl加密，会报530错误
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			// 2、创建定义整个应用程序所需的环境信息的 Session 对象
			Session session = Session.getInstance(properties);
			// 设置调试信息在控制台打印出来
			session.setDebug(false);
			// 3、创建邮件的实例对象
			Message msg = getMimeMessageNew(session, sendEmailAddress, recipientAddress, mailContent,subject);
			// 4、根据session对象获取邮件传输对象Transport
			transport = session.getTransport();
			// 设置发件人的账户名和密码
			transport.connect(sendEmailAddress, sendEmailPassword);
			// 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
			transport.sendMessage(msg, msg.getAllRecipients());
			flag = true;
		} catch (NoSuchProviderException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (MessagingException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (Exception e) {
			flag = false;
			logger.error(e.getMessage());
		} finally {
			// 5、关闭邮件连接
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.error("邮件发送异常",e.getMessage());
				}

			}
		}
		return flag;
	}
	
	private  MimeMessage getMimeMessageNew(Session session, String senderAddress, String recipientAddress,
			String mailContent,String subject) {
		// 创建一封邮件的实例对象
		MimeMessage msg = null;
		try {
			msg = new MimeMessage(session);
			// 设置发件人地址
			msg.setFrom(new InternetAddress(senderAddress));
			/**
			 * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行 MimeMessage.RecipientType.TO:发送
			 * MimeMessage.RecipientType.CC：抄送 MimeMessage.RecipientType.BCC：密送
			 */
			//设置自定义发件人昵称  
	        String nick="";  
	        try {  
	            nick=javax.mail.internet.MimeUtility.encodeText(Constants.EMAIL_NICK,"utf-8",null);  
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        } 
			// 设置发件人地址
			msg.setFrom(new InternetAddress(nick+" <"+sendEmailAddress+">"));
			msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
			// 设置邮件主题
			msg.setSubject(subject, "UTF-8");
			// 设置邮件正文
			msg.setContent(mailContent, "text/html;charset=UTF-8");
			// 设置邮件的发送时间,默认立即发送
			msg.setSentDate(new Date());
		} catch (AddressException e) {
			logger.error(e.getMessage());
		} catch (MessagingException e) {
			logger.error(e.getMessage());
		}

		return msg;
	}
	
	/**
	 * 系统内部邮件通知
	 * @param recipientAddress
	 *            收件地址
	 * @return
	 * @throws Exception
	 */
	public  Boolean sendNoticeMail(String recipientAddress, String notice, String mailContent) {
		Transport transport = null;
		Boolean flag = false;
		try {
			// 创建连接对象 连接到邮件服务器
			Properties properties = new Properties();
			// 设置用户的认证方式
			properties.setProperty("mail.smtp.auth", "true");

			// 设置传输协议
			properties.setProperty("mail.transport.protocol", "smtp");

			// 设置发件人的SMTP服务器地址
			properties.setProperty("mail.smtp.host", "smtp.mxhichina.com");
			// 开启ssl加密，如果没有ssl加密，会报530错误
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			// 2、创建定义整个应用程序所需的环境信息的 Session 对象
			Session session = Session.getInstance(properties);
			// 设置调试信息在控制台打印出来
			session.setDebug(true);
			// 3、创建邮件的实例对象
			MimeMessage msg = new MimeMessage(session);
			//设置自定义发件人昵称  
	        String nick="";  
	        try {
	        	nick=javax.mail.internet.MimeUtility.encodeText(Constants.EMAIL_NICK,"utf-8",null);
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        } 
			// 设置发件人地址
			msg.setFrom(new InternetAddress(nick+" <"+sendEmailAddress+">"));
			/**
			 * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行 MimeMessage.RecipientType.TO:发送
			 * MimeMessage.RecipientType.CC：抄送 MimeMessage.RecipientType.BCC：密送
			 */
			Address[] internetAddressTo = (new InternetAddress()).parse(recipientAddress);
			msg.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
			// 设置邮件主题
			msg.setSubject("门墩儿系统通知-"+notice, "UTF-8");
			// 设置邮件正文
			msg.setContent(mailContent, "text/html;charset=UTF-8");
			// 设置邮件的发送时间,默认立即发送
			msg.setSentDate(new Date());
			// 4、根据session对象获取邮件传输对象Transport
			transport = session.getTransport();
			// 设置发件人的账户名和密码
			transport.connect(sendEmailAddress, sendEmailPassword);
			// 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
			transport.sendMessage(msg, msg.getAllRecipients());
			flag = true;
		} catch (NoSuchProviderException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (MessagingException e) {
			flag = false;
			logger.error(e.getMessage());
		} catch (Exception e) {
			flag = false;
			logger.error(e.getMessage());
		} finally {
			// 5、关闭邮件连接
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.error("邮件发送异常",e.getMessage());
				}

			}
		}
		return flag;
	}
	
}
