package com.gree.mall.manager.utils.email;


import cn.hutool.core.date.DateUtil;
import com.sun.mail.imap.IMAPStore;
import lombok.extern.slf4j.Slf4j;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

@Slf4j
public class EmailUtilsNew {

    private static final String ALIDM_SMTP_HOST = "smtp.exmail.qq.com";
    private static final int ALIDM_SMTP_PORT = 80;// 或80



    // 发件人的账号 和 密码
    private String user;
    private String password;

    public EmailUtilsNew() {
            this("zhongju@gm.zfire.top", "PRivate123");
    }

    public EmailUtilsNew(String user, String password) {
        this.user = user;
        this.password = password;
    }

//    public static void main(String[] args) throws IOException, MessagingException {
//        //new EmailUtilsNew().send("448797381@qq.com", "测试1", "nihao显示");
//        //new EmailUtilsNew().send("448797381@qq.com", "测试1", "市劳动纠纷联赛积分了","B:/21.11仓储维修.xls");
//        new EmailUtilsNew().receEmail();
//    }

    /**
     * 发送邮件
     * @param toEmail  收件人邮箱地址
     * @param subject 邮件标题
     * @param content  邮件内容 可以是html内容
     */
    public void send(String toEmail, String subject, String content) {
        Session session = loadMailSession();
        // session.setDebug(true);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(session);
        try {
            // 设置发件人
            message.setFrom(new InternetAddress(user));
            Address[] a = new Address[1];
            a[0] = new InternetAddress(user);
            message.setReplyTo(a);
            // 设置收件人
            InternetAddress to = new InternetAddress(toEmail);
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            log.error("【发送邮件失败】",e);
        }
    }


    /**
     * 发送邮件 带附件
     * @param toEmail  收件人邮箱地址
     * @param subject  邮件标题
     * @param content  邮件内容 可以是html内容
     * @param attachPath 附件路径
     */
    public void send(String toEmail,String emailReceAccount, String subject, String content, String attachPath) {
        Session session = loadMailSession();

        MimeMessage mm = new MimeMessage(session);
        try {
            //mm.addHeader("Disposition-Notification-To", "448797381@qq.com");
            //发件人
            mm.setFrom(new InternetAddress(user));
            //收件人
            mm.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); // 设置收件人

            Address[] a = new Address[1];
            a[0] = new InternetAddress(emailReceAccount);
            mm.setReplyTo(a);
            // mm.setRecipient(Message.RecipientType.CC, new
            // InternetAddress("XXXX@qq.com")); //设置抄送人
            //标题
            mm.setSubject(subject);
            //内容
            Multipart multipart = new MimeMultipart();
            //body部分
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);

            //附件部分
            BodyPart attachPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(attachPath);
            attachPart.setDataHandler(new DataHandler(fileDataSource));
            attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
            multipart.addBodyPart(attachPart);

            mm.setContent(multipart);
            Transport.send(mm);
        } catch (Exception e) {
            String err = e.getMessage();
            // 在这里处理message内容， 格式是固定的
            System.out.println(err);
        }

    }

    public static void main(String[] args) throws IOException, MessagingException {
        new com.gree.mall.manager.utils.email.EmailUtilsNew("15920909481@163.com","WVLNTJADXDSHHSNU").receEmail("","");
    }


    /**
     * 判断是否收到了保险回执
     * @throws MessagingException
     * @throws IOException
     */
    public Boolean receEmail(String receEmail,String sendBatch) throws MessagingException, IOException {

        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", ALIDM_SMTP_HOST);
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.auth.login.disable", "true");
        props.setProperty("mail.imap.ssl.enable", "true");

        HashMap IAM = new HashMap();
        //带上IMAP ID信息，由key和value组成，例如name，version，vendor，support-email等。
        // 这个value的值随便写就行
        IAM.put("name","李斌");
        IAM.put("version","1.0.0");
        IAM.put("vendor","myclient");
        IAM.put("support-email","17607626121@163.com");

        Session session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication(user, password);
            }
        });
        Store store = (IMAPStore)session.getStore("imap");
        // imap.qq.com
        store.connect(ALIDM_SMTP_HOST, user, password);


        // 获得邮箱内的邮件夹Folder对象，以"只读"打开
        Folder inbox = store.getFolder("INBOX");

        //folder.open(Folder.READ_ONLY);
        inbox.open(Folder.READ_WRITE);


        // 获得邮件夹Folder内的所有邮件Message对象
        Message[] messages = inbox.getMessages();

        int mailCounts = messages.length;
        for(int i = messages.length-1; i > messages.length -20; i--) {

            String subject = messages[i].getSubject();
            String from = (messages[i].getFrom()[0]).toString();
            Date receivedDate = messages[i].getReceivedDate();
            Flags flags = messages[i].getFlags();

            if (subject.split("-").length < 2)
                continue;
            if (!subject.split("-")[1].equals(sendBatch) ){
                continue;
            }
            //今天接收的邮件
            if(receivedDate.getTime() > DateUtil.beginOfDay(new Date()).getTime() && from.indexOf(receEmail) > -1){
                messages[i].setFlag(Flags.Flag.SEEN, true);
                inbox.close(false);
                store.close();
                return true;
            }

//            System.out.println("第 " + (i+1) + "封邮件的主题：" + subject);
//            System.out.println("第 " + (i+1) + "封邮件的发件人地址：" + from);
//
//            System.out.println("是否打开该邮件(yes/no)?：");
//            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//            String input = br.readLine();
//            if("yes".equalsIgnoreCase(input)) {
//                // 直接输出到控制台中
//                messages[i].writeTo(System.out);
//            }
        }
        inbox.close(false);
        store.close();
        return false;
    }







    private Session loadMailSession() {
        try {
            // 配置发送邮件的环境属性
            final Properties props = new Properties();
            // 表示SMTP发送邮件，需要进行身份验证
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", ALIDM_SMTP_HOST);
            // props.put("mail.smtp.port", ALIDM_SMTP_PORT);
            // 如果使用ssl，则去掉使用25端口的配置，进行如下配置,
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.port", "465");
            // 发件人的账号
            props.put("mail.user", user);
            // 访问SMTP服务时需要提供的密码
            props.put("mail.password", password);
            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            return Session.getInstance(props, authenticator);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("mail session is null");
        }
        return null;
    }


}
