package com.fdkankan.sms;

import cn.hutool.core.util.StrUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;

@Slf4j
public class SendMailAcceUtils {

    public final static String subject = "四维看看购物发票详情  ";

    public final static String subjectinvoice = "您的四维看看订单【${ordernum}】电子发票已开具 ";
    public final static String msg =
            "<div>尊敬的【${username}】您好：</div><br>"  +
                    "<div>感谢您在四维看看（www.4dkankan.com）消费！</div><br>" +
                    "<div>四维看看已经为您开具订单【${ordernum}】的电子普通发票，发票数量共计一张。</div><br>" +
                    "<div>您之所以收到这封邮件，是因为您曾经注册成为四维看看的用户。本邮件由四维看看系统自动发出，请勿直接回复！</div><br>" +
                    "<div>如果您有任何疑问或建议，请拨打客服电话联系我们。（客服电话：0756-6996790-800）</div><br>" +
                    "<div>四维看看官方人员不会主动联系客户并要求提供您的账号电邮及账户密码等个人资料。</div><br>" +
                    "<div>若收到可疑人物利用四维看看讯息要求取得您的个人资料，请勿配合并尽快拨打客服电话联系我们</div><br> ";

    public final static String CN_CODE_SUBJECT = "四维看看验证码";


    public final static String EN_CODE_SUBJECT = "4Dkankan verification code";

    public final static String EN_CODE_SUBJECT_USA = "FALCON VISUAL";

    public final static String CN_CODE_MSG = "<div>您的验证码为：<b>${code}</b></div><br>" +
            "<div>请在5分钟范围内输入验证码以完成身份验证，如非本人操作，请忽略此消息。</div><br>" +
            "<br>" +
            "<div>谢谢，</div><br>" +
            "<div>四维时代</div><br>" +
            "<br>" +
            "<div>注意：此信是系统自动发出, 请不要直接\"回复\"本邮件。如果您还有任何疑问，请联系我们的客户服务部门。" +
            "<br><br><br>" +
            "<div style=\"color:#909090;font-family:Arial Narrow;font-size:12px\">------------------</div>" +
            "<div style=\"color:#909090;font-family:Arial Narrow;font-size:12px\"><img src=\"https://4dkk.4dage.com/loading/email.png\"></div>" +
            "<div><span style=\" color: rgb(17, 31, 44) ; font-size: 10pt \"><b><i>Tel：</i></b></span>" +
            " <span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 8pt;\">400-669-8025</span></div><div><span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 10pt; font-style: italic; font-weight: bold;\">Add：</span><span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 8pt;\">珠海市高新区唐家湾镇港湾大道港湾一号港11</span><br style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-clip: padding-box; color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><i><font size=\"1\">Building 11, Tech Bay, Harbour Road, Hi-tech Zone, Zhuhai, Guangdong</font></i></span><br style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-clip: padding-box; color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><span style=\" color: rgb(17, 31, 44) ; font-size: 10pt; ; ; ; ; ; ; ; ; ; ; \"><b><i>Web：</i></b></span><a href=\"http://www.4dage.com/\" target=\"_blank\" style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: padding-box; background-clip: padding-box; outline: none; cursor: pointer; transition: color 0.3s ease 0s ; ; ; ; ; ; ; ; ; ; ; ; ; \">www.4dage.com</a><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \">   </span><a href=\"http://www.cgaii.com/\" target=\"_blank\" style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: padding-box; background-clip: padding-box; outline: none; cursor: pointer; transition: color 0.3s ease 0s ; ; ; ; ; ; ; ; ; ; ; ; ; \">www.cgaii.com</a><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"> </span></div>\n";

    public final static String EN_CODE_MSG =
            "<div>Your vertification code is <b>${code}</b>. Thank you for using 4DKanKan, please complete your identity verification by entering this code in 5 minutes. Please ignore this message if the operation wasn't done by yourself.</div><br>" +
                    "<br>" +
                    "<div>Note: This is an auto-sent Email, please do not reply directly. May you have any questions, please contact our customer service.</div>" +
                    "<br><br><br>" +
                    "<div style=\"color:#909090;font-family:Arial Narrow;font-size:12px\">------------------</div>" +
                    "<div style=\"color:#909090;font-family:Arial Narrow;font-size:12px\"><img src=\"https://4dkk.4dage.com/loading/email.png\"></div>" +
                    "<div><span style=\" color: rgb(17, 31, 44); font-size: 10pt \"><b><i>Tel：</i></b></span>" +
                    " <span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 8pt;\">400-669-8025</span></div><div><span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 10pt; font-style: italic; font-weight: bold;\">Add：</span><span style=\"color: rgb(17, 31, 44); font-family: &quot;Microsoft YaHei UI&quot;; font-size: 8pt;\">珠海市高新区唐家湾镇港湾大道港湾一号港11</span><br style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-clip: padding-box; color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><i><font size=\"1\">Building 11, Tech Bay, Harbour Road, Hi-tech Zone, Zhuhai, Guangdong</font></i></span><br style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-clip: padding-box; color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"><span style=\" color: rgb(17, 31, 44) ; font-size: 10pt; ; ; ; ; ; ; ; ; ; ; \"><b><i>Web：</i></b></span><a href=\"http://www.4dage.com/\" target=\"_blank\" style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: padding-box; background-clip: padding-box; outline: none; cursor: pointer; transition: color 0.3s ease 0s ; ; ; ; ; ; ; ; ; ; ; ; ; \">www.4dage.com</a><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \">   </span><a href=\"http://www.cgaii.com/\" target=\"_blank\" style=\" -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: padding-box; background-clip: padding-box; outline: none; cursor: pointer; transition: color 0.3s ease 0s ; ; ; ; ; ; ; ; ; ; ; ; ; \">www.cgaii.com</a><span style=\" color: rgb(17, 31, 44) ; ; ; ; ; ; ; ; ; ; ; ; \"> </span></div>\n";

    public final static String EN_CODE_MSG_USA =
            "<div> Hello! </div><br>" +
                    "<div> Your vertification code is <b>${code}</b>.. Thank you for using Falcon Visual, please complete your identity verification by entering this code in 5 minutes. Please ignore this message.</div><br>"+
                    "<div> if the operation wasn't done by yourself.</div><br>" +
                    "<br><br><br>" +
                    "<div> Note: This is an auto-sent Email, please do not reply directly. May you have any questions, please contact our customer service.</div><br>";

    public static void main(String[] args) throws GeneralSecurityException {

        String msg = "<p>Dear Valued Customers,&nbsp;</p>\n" +
                "<p>&nbsp;</p>\n" +
                "<p>The scene \"Hotel\" has been successfully calculated,please review the following:&nbsp;<a href=\"scene_link\" target=\"_blank\" rel=\"noopener\">scene_link</a>#/&nbsp;</p>\n" +
                "<p>&nbsp;</p>\n" +
                "<p>If you need to edit the sense, the User Manual can provide instructions:&nbsp;<a href=\"help_link\" target=\"_blank\" rel=\"noopener\">help_link</a>#/service/use/help&nbsp;</p>\n" +
                "<p>&nbsp;</p>\n" +
                "<p>This email was automatically sent by the 4DAGE, please do not reply.&nbsp;</p>\n" +
                "<p>&nbsp;</p>\n" +
                "<p>Sincerely,&nbsp;</p>\n" +
                "<p>4Dage Support Team</p>";
        msg = msg.replaceAll("scene_link", "https://test.4dkankan.com/spg.html?m=KJ-sCqJv2aS").replaceAll("help_link", "https://test.4dkankan.com/spg.html?m=KJ-sCqJv2aS");

        SendMailAcceUtils.sendMail("4Dkankan@4dage.com", "6996790AAaa",
                "smtp.exmail.qq.com", "767383594@qq.com", "看看吧", msg, null);
    }


    /**
     *
     * @param userName 发送人账号
     * @param password 发送人密码
     * @param stmpHost smtp服务器地址
     * @param receive  接收人邮箱地址
     * @param subject  主题
     * @param msg      消息主题
     * @param filename 附件地址
     * @return
     * @throws GeneralSecurityException
     */
    public static boolean sendMail(String userName, String password, String stmpHost,
                                   String receive, String subject, String msg, String filename)
            throws GeneralSecurityException {
        if (StrUtil.isEmpty(userName)
                || StrUtil.isEmpty(password)
                || StrUtil.isEmpty(stmpHost)
                || StrUtil.isEmpty(receive)) {
            return false;
        }


        // smtp服务器的链接信息
        Properties properties = new Properties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", stmpHost);

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication(userName, password); // 发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(userName));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));

            // Set Subject: 主题文字
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(msg);

            // 创建多重消息
            MimeMultipart multipart = new MimeMultipart("mixed");

            if(StringUtils.isNotEmpty(filename)){
                // 附件部分
                messageBodyPart = new MimeBodyPart();
                // 设置要发送附件的文件路径
                DataSource source = new FileDataSource(filename);
                messageBodyPart.setDataHandler(new DataHandler(source));

                // messageBodyPart.setFileName(filename);
                // 处理附件名称中文（附带文件路径）乱码问题
                messageBodyPart.setFileName(MimeUtility.encodeText(filename));
                multipart.addBodyPart(messageBodyPart);
            }

            //html代码部分
            MimeBodyPart htmlPart = new MimeBodyPart();
            multipart.addBodyPart(htmlPart);
            //html代码
            htmlPart.setContent(msg, "text/html;charset=utf-8");

            // 发送完整消息
            message.setContent(multipart);

            // 发送消息
            log.info("执行发送邮件");
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            log.info("邮件发送成功");
            return true;
        } catch (MessagingException e) {
            log.error("发送邮件失败",e);
        } catch (UnsupportedEncodingException e) {
            log.error("发送邮件失败",e);
        }
        return false;
    }

    /**
     * 发送带附件的邮件
     *
     * @param receive
     *            收件人
     * @param subject
     *            邮件主题
     * @param msg
     *            邮件内容
     * @param filename
     *            附件地址
     * @return
     * @throws GeneralSecurityException
     */
    public static boolean sendMail(String receive, String subject, String msg, String filename)
            throws GeneralSecurityException {
        if (StringUtils.isEmpty(receive)) {
            return false;
        }

        // 发件人电子邮箱
        final String from = "4Dkankan@4dage.com";
        // 发件人电子邮箱密码
        final String pass = "6996790AAaa";

        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.exmail.qq.com";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));

            // Set Subject: 主题文字
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(msg);

            // 创建多重消息
            MimeMultipart multipart = new MimeMultipart("mixed");

            if(StringUtils.isNotEmpty(filename)){
                // 附件部分
                messageBodyPart = new MimeBodyPart();
                // 设置要发送附件的文件路径
                DataSource source = new FileDataSource(filename);
                messageBodyPart.setDataHandler(new DataHandler(source));

                // messageBodyPart.setFileName(filename);
                // 处理附件名称中文（附带文件路径）乱码问题
                messageBodyPart.setFileName(MimeUtility.encodeText(filename));
                multipart.addBodyPart(messageBodyPart);
            }

            //html代码部分
            MimeBodyPart htmlPart = new MimeBodyPart();
            multipart.addBodyPart(htmlPart);
            //html代码
            htmlPart.setContent(msg, "text/html;charset=utf-8");

            // 发送完整消息
            message.setContent(multipart);

            // 发送消息
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送带附件的邮件
     *
     * @param receive
     *            收件人
     * @param subject
     *            邮件主题
     * @param msg
     *            邮件内容
     * @param filename
     *            附件地址
     * @return
     * @throws GeneralSecurityException
     */
    public static boolean sendMailUsa(String receive, String subject, String msg, String filename)
            throws GeneralSecurityException {
        if (StringUtils.isEmpty(receive)) {
            return false;
        }

//        // 发件人电子邮箱
//        final String from = "4Dkankan@4dage.com";
//        // 发件人电子邮箱密码
//        final String pass = "6996790AAaa";
//
//        // 指定发送邮件的主机为 smtp.qq.com
//        String host = "smtp.exmail.qq.com"; // 邮件服务器

        // 发件人电子邮箱
        final String from = "brokereasierphoto@gmail.com";
        // 发件人电子邮箱密码
        final String password = "xkodciewgzreicyc";


        // 获取系统属性
        Properties prop = new Properties();
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getInstance(prop, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));

            // Set Subject: 主题文字
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(msg);

            // 创建多重消息
            MimeMultipart multipart = new MimeMultipart("mixed");

            if(StringUtils.isNotEmpty(filename)){
                // 附件部分
                messageBodyPart = new MimeBodyPart();
                // 设置要发送附件的文件路径
                DataSource source = new FileDataSource(filename);
                messageBodyPart.setDataHandler(new DataHandler(source));

                // messageBodyPart.setFileName(filename);
                // 处理附件名称中文（附带文件路径）乱码问题
                messageBodyPart.setFileName(MimeUtility.encodeText(filename));
                multipart.addBodyPart(messageBodyPart);
            }

            //html代码部分
            MimeBodyPart htmlPart = new MimeBodyPart();
            multipart.addBodyPart(htmlPart);
            //html代码
            htmlPart.setContent(msg, "text/html;charset=utf-8");

            // 发送完整消息
            message.setContent(multipart);

            // 发送消息
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

}
