package cn.estsh.i3plus.core.apiservice.util;

import cn.estsh.i3plus.core.api.iservice.busi.ISysConfigService;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.MailConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @Description : 邮件工具类
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-14 19:24
 * @Modify:
 **/
@Component
public class MailUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);

    // 收件人
    private Address[] to = null;
    private Address[] cc = null;
    private String from = "";
    private String nick = "";
    private String title = "";
    private String content = "";
    private String smtpHost = "";
    private int smtpPort = 25;
    private String content_type = "";

    private String smtpUser = "";
    private String smtpPassword = "";
    private boolean isAuthenticationSMTP = false;

    @Autowired
    private ISysConfigService sysConfigService;

    //初始化服务器邮箱参数
    public MailUtil init() {
        this.smtpHost = sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_HOST).getConfigValue();
        this.smtpPort = Integer.parseInt(sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_PORT).getConfigValue());
        this.from = sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_USER).getConfigValue();
        this.nick = sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_NICK).getConfigValue();
        this.smtpUser = sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_USER).getConfigValue();
        this.smtpPassword = sysConfigService.getSysConfigByCode(PlatformConstWords.MAIL_PASSWORD).getConfigValue();
        this.isAuthenticationSMTP = true;

        return this;
    }

    //初始化服务器邮箱参数
    public MailUtil init(MailConfig mailConfig) {
        this.smtpHost = mailConfig.getMailHost();
        this.smtpPort = mailConfig.getMailPort();
        this.from = mailConfig.getMailUser();
        this.nick = mailConfig.getMailNick();
        this.smtpUser = mailConfig.getMailUser();
        this.smtpPassword = mailConfig.getMailPassword();
        this.isAuthenticationSMTP = true;

        return this;
    }
    /**
     * 设置收件人地址
     *
     * @param nick
     *            收件人Email地址
     */
    public void setNick(String nick) {
        this.nick = nick;
    }


    /**
     * 设置收件人地址
     *
     * @param aEmail
     *            收件人Email地址
     */
    public void setTo(String aEmail) {
        String[] s = new String[1];
        s[0] = aEmail;
        this.to = getAddress(s);
    }

    /**
     * 设置多个收件人地址
     *
     * @param Emails
     *            收件人Email地址
     */
    public void setTo(String[] Emails) {
        this.to = getAddress(Emails);
    }

    /**
     * 设置抄送地址
     *
     * @param aEmail
     *            抄送地址
     */
    public void setCC(String aEmail) {
        String[] s = new String[1];
        s[0] = aEmail;
        this.cc = getAddress(s);
    }

    /**
     * 设置多个抄送地址
     *
     * @param Emails
     *            抄送地址
     */
    public void setCC(String[] Emails) {
        this.cc = getAddress(Emails);
    }

    /**
     * 设置邮件主题
     *
     * @param mailTitle
     *            邮件主题
     */
    public void setSubject(String mailTitle) {
        this.title = mailTitle;
    }

    /**
     * 设置邮件文字内容
     *
     * @param mailContent
     *            邮件文字内容
     */
    public void setBody(String mailContent) {
        this.content = mailContent;
    }

    /**
     * 设置邮件字符类型
     *
     * @param contentType
     *            请从CommonConstWords.MAIL_MODE_TEXT和MAIL_MODE_HTML中选择
     */
    public void setContentType(String contentType) {
        this.content_type = contentType;
    }

    private Address[] getAddress(String[] add) {
        Address[] a = new Address[add.length];
        for (int i = 0; i < add.length; i++) {
            try {
                a[i] = new InternetAddress(add[i]);
            } catch (AddressException ex) {
                ex.printStackTrace();
            }
        }
        return a;
    }
    /**
     * 发送邮件
     */
    public void send() throws UnsupportedEncodingException, MessagingException {
            Properties server = new Properties();
            server.put("mail.smtp.port", String.valueOf(this.smtpPort));
            server.put("mail.smtp.host", this.smtpHost);
            if (this.isAuthenticationSMTP) {
                server.put("mail.smtp.auth", "true");
            }

            Session conn = Session.getInstance(server, null);

            MimeMessage msg = new MimeMessage(conn);
            if (nick != null && !"".equals(nick)) {
                nick = MimeUtility.encodeText(nick, MimeUtility.mimeCharset("gb2312"), null);
                msg.setSubject(nick);
                msg.setFrom(new InternetAddress(nick + " <" + from + ">"));
            } else {
                msg.setFrom(new InternetAddress(this.from));
            }
            // 收件人
            if (this.to != null) {
                msg.setRecipients(Message.RecipientType.TO, this.to);
            }
            // 抄送
            if (this.cc != null) {
                msg.setRecipients(Message.RecipientType.CC, this.cc);
            }

            msg.setSubject( MimeUtility.encodeText(this.title, MimeUtility.mimeCharset("gb2312"), null));
            msg.setSubject(this.title);

            // 消息主体内容 处理
            this.content = this.content == null ? "" : this.content;

            msg.setContent(this.content, this.content_type);

            msg.saveChanges();
            if (this.isAuthenticationSMTP) {
                Transport transport = conn.getTransport("smtp");
                transport.connect(this.smtpHost, this.smtpUser, this.smtpPassword);
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();
            } else {
                Transport.send(msg, msg.getAllRecipients());
            }
            LOGGER.info("邮件发送成功");
    }
}
