package com.goafanti.common.utils;

import com.goafanti.common.bo.EmailBo;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SendEmailUtil {
	private static Session session;
	private static volatile SendEmailUtil singleton;
	private SendEmailUtil() {}
	public static SendEmailUtil getInstance() {
      if (singleton == null) {
          synchronized (SendEmailUtil.class) {
              if (singleton == null) {
                  singleton = new SendEmailUtil();
                  session = getSession();
              }
          }
      }
      return singleton;
  }
	public static final String HOST = "smtp.163.com";
	public static final String PORT = "465";
	public static final String AUTH_USER_NICKNAME = "湖南科德信息咨询集团有限公司";
	public static final String FROM = "13875952633@163.com";// 发件人的email
	public static final String PWD = "kede2018";// 发件人密码
	public static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";



	private static Session getSession() {
		Properties props = new Properties();

		//开启安全协议
        MailSSLSocketFactory sf = null;
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        props.setProperty("mail.smtp.socketFactory.port", PORT);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");// 注意是字符串的true,不是boolean类型的true
		// 这一套是465端口
		props.setProperty("mail.smtp.host", HOST);// 设置服务器地址
		props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);// 设置协议
		props.setProperty("mail.smtp.port", PORT);// 设置端口
		props.put("mail.smtp.auth", "true");// 注意是字符串的true,不是boolean类型的true

		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(FROM, PWD);
			}

		};
		Session session = Session.getDefaultInstance(props, authenticator);
		System.out.println("session hash code" + session.hashCode());
		return session;
	}

	/**
	 * 如果要给多个人发,请EmailBo 的 address , addressee用逗号隔开 注意要一一对应且个数相等
	 * @param emailBo
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void send(EmailBo emailBo)
			throws MessagingException, UnsupportedEncodingException {
//		 Session session = getSession();
		// Instantiate a message
		Message msg = new MimeMessage(session);
		// Set message attributes
		msg.setFrom(new InternetAddress(MimeUtility.encodeText(AUTH_USER_NICKNAME) +"<" +  FROM + ">"));
//		msg.setFrom(new InternetAddress(FROM));
		String[] adds =  emailBo.getAddress().split(",");
		Date date = new Date();
		for (int i = 0; i < adds.length; i++) {
			InternetAddress internetAddress = new InternetAddress(adds[i]);
			msg.setRecipient(Message.RecipientType.TO, internetAddress);
			msg.setSubject(emailBo.getSubject());
			msg.setSentDate(date);
			msg.setContent(emailBo.format(), "text/html;charset=utf-8");
			// Send the message
			Transport.send(msg);
		}
	}

	/**
	 * 如果要给多个人发,请EmailBo 的 address , addressee用逗号隔开 注意要一一对应且个数相等
	 * @param emailBo
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void patentSend(EmailBo emailBo)
			throws MessagingException, UnsupportedEncodingException {
		// Session session = getSession();
		Message msg = new MimeMessage(session);

		// Set message attributes
		msg.setFrom(new InternetAddress(MimeUtility.encodeText(AUTH_USER_NICKNAME) +"<" +  FROM + ">"));
		emailBo.SetEnd("");
//		msg.setFrom(new InternetAddress(FROM));
		String[] adds =  emailBo.getAddress().split(",");
//		String[] ees =  emailBo.getAddressee().split(",");
		for (int i = 0; i < adds.length; i++) {
			InternetAddress internetAddress = new InternetAddress(adds[i]);
			msg.setRecipient(Message.RecipientType.TO, internetAddress);
			msg.setSubject(emailBo.getSubject());
			msg.setSentDate(new Date());
			msg.setContent(emailBo.getContent(), "text/html;charset=utf-8");
			// Send the message
			Transport.send(msg);
		}
	}

	public static boolean isEmail(String email){
		if (StringUtils.isEmpty(email)) {
			return false;
		}
    	//邮箱正则表达式
        String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(email);
        return m.matches();
    }






	public static void main(String[] args) {
		  EmailBo emailBo = new EmailBo( "专利提醒失败",  "anderx@dingtalk.com",  "平台",  "系统", "专利提醒失败");
				try {
					SendEmailUtil.getInstance().send(emailBo);
				} catch (UnsupportedEncodingException | MessagingException e) {
					e.printStackTrace();
				}
	}

}
