package com.youchain.utils.Email;

import com.youchain.config.RsaProperties;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.service.dto.UserDto;
import com.youchain.modules.system.service.dto.UserQueryCriteria;
import com.youchain.modules.system.service.impl.UserServiceImpl;
import com.youchain.utils.RsaUtils;
import com.youchain.utils.SecurityUtils;
import com.youchain.utils.SpringContextHolder;
import com.youchain.utils.UserUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class EmailUtils {

    /****
     * 发送邮件（当前登录用户）
     * @param title
     * @param msg
     * @param to
     * @return
     */
    public static ApiResult  sendByCurrUser(String title,String msg,String[] to){
        try{
            //*****获取当前登录用户
            /*Long userID =SecurityUtils.getCurrentUserId();
            UserServiceImpl userService = SpringContextHolder.getBean(UserServiceImpl.class);
            UserQueryCriteria userQueryCriteria =new UserQueryCriteria();
            userQueryCriteria.setId(userID);
            List<UserDto> users=userService.queryAll(userQueryCriteria);
            if(users.size()<=0){
                return  ApiResult.fail(400,"用户验证失败","");
            }
            UserDto userDto=users.get(0);*/
            ApiResult re_str=send(title,msg,to);
            return  re_str;
        }catch(Exception e){
            System.out.println("异常："+e.toString());
            return  ApiResult.fail(400,"验证码发送失败：邮箱账号密码错误","");
        }
    }


    public static ApiResult send(String title,String msg,String[] to){
        try{
            String email = "huoj@youchain56.com";
            String emailPwd = "Jin982011";
            String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,emailPwd);


            //设置SSL连接、邮件环境
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties props = System.getProperties();
            //协议
            //props.setProperty("mail.transport.protocol", "smtp");

            props.setProperty("mail.smtp.host", "smtp.mxhichina.com");//smtp服务器地址
            //props.setProperty("mail.smtp.port", "25");//非加密端口
            // 使用ssl加密方式，进行如下配置：
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", "465");

            props.setProperty("mail.smtp.auth", "true");//表示SMTP发送邮件，需要进行身份验证
            props.setProperty("mail.smtp.from",email);//mailfrom 参数
            props.setProperty("mail.user",email);//发件人的账号
            props.setProperty("mail.password",emailPwd);// 发件人的账号的密码，如果开启三方客户端安全密码请使用新生产的密码
            //建立邮件会话
            Session session = Session.getInstance(props, new Authenticator() {
                //身份认证
                protected PasswordAuthentication getPasswordAuthentication() {
                    //发件人的账号、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            });
            //建立邮件对象
            MimeMessage message = new MimeMessage(session);
            //设置邮件的发件人
            InternetAddress from = new InternetAddress(email,email); //from 参数,可实现代发，注意：代发容易被收信方拒信或进入垃圾箱。
            message.setFrom(from);
            //设置邮件的收件人
            //to = new String []{"768863620@qq.com"};//收件人列表
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i=0;i<to.length;i++){
                //System.out.println("发送到：" + to[i]);
                sendTo[i] = new InternetAddress(to[i]);
            }

            //传入收件人
            message.setRecipients(Message.RecipientType.TO,sendTo);
            //设置邮件的主题
            message.setSubject(title);
            //设置邮件的文本
            String content=msg;
            message.setContent(content,"text/html;charset=UTF-8");
            //设置时间
            message.setSentDate(new Date());
            message.saveChanges();
            //发送邮件
            Transport.send(message);

            System.out.println("发送成功！");

            return  ApiResult.success("邮件发送成功","");
        }catch(Exception e){
            System.out.println("异常："+e.toString());
            return  ApiResult.fail(400,"验证码发送失败：邮箱账号密码错误","");
        }
    }


    public static ApiResult sendNodecrypPwd(String title,String msg,String[] to){
        try{
            //邮箱账号密码
            String email = "huoj@youchain56.com";
            String emailPwd = "Jin982011";
            //设置SSL连接、邮件环境
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties props = System.getProperties();
            //协议
            //props.setProperty("mail.transport.protocol", "smtp");

            props.setProperty("mail.smtp.host", "smtp.mxhichina.com");//smtp服务器地址
            //props.setProperty("mail.smtp.port", "25");//非加密端口
            // 使用ssl加密方式，进行如下配置：
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", "465");

            props.setProperty("mail.smtp.auth", "true");//表示SMTP发送邮件，需要进行身份验证
            props.setProperty("mail.smtp.from", email);//mailfrom 参数
            props.setProperty("mail.user",email);//发件人的账号
            props.setProperty("mail.password",emailPwd);// 发件人的账号的密码，如果开启三方客户端安全密码请使用新生产的密码
            //建立邮件会话
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                //身份认证
                protected PasswordAuthentication getPasswordAuthentication() {
                    //发件人的账号、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            });
            //建立邮件对象
            MimeMessage message = new MimeMessage(session);
            //设置邮件的发件人
            InternetAddress from = new InternetAddress(email,email); //from 参数,可实现代发，注意：代发容易被收信方拒信或进入垃圾箱。
            message.setFrom(from);
            //设置邮件的收件人
            //to = new String []{"768863620@qq.com"};//收件人列表
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i=0;i<to.length;i++){
                //System.out.println("发送到：" + to[i]);
                sendTo[i] = new InternetAddress(to[i]);
            }

            //传入收件人
            message.setRecipients(Message.RecipientType.TO,sendTo);
            //设置邮件的主题
            message.setSubject(title);
            //设置邮件的文本
            String content=msg;
            message.setContent(content,"text/html;charset=UTF-8");
            //设置时间
            message.setSentDate(new Date());
            message.saveChanges();
            //发送邮件
            Transport.send(message);

            System.out.println("发送成功！");
            return  ApiResult.success("邮件发送成功","");
        }catch(Exception e){
            System.out.println("异常："+e.toString());
            return  ApiResult.fail(400,"验证码发送失败：邮箱账号密码错误","");
        }
    }


    public static String meetingEmail = "<p>&nbsp;&nbsp;&nbsp;&nbsp;您好！</p ><p>&nbsp; &nbsp; " +
            "XXX邀请你参加 (会议主题) ，本次会议在（会议地点+线上ID）召开，开始时间，预计 X小时，请安排好工作时间,准时参加会议。</p ><p>" +
            "&nbsp; &nbsp; 会议组织人：XXX<br/></p ><p>&nbsp; &nbsp;&nbsp;</p ><p>&nbsp; &nbsp;&nbsp;<br/></p >";
}
