package com.quinn.intergration;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.EmailType;
import com.quinn.common.QuinnConstant;
import com.quinn.pojo.Email;
import com.quinn.service.EmailService;
import com.quinn.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * 使用@multiavatar生成头像
 * https://api.multiavatar.com/
 */
@Component
public class SendBMail {

    private static final Logger log = LoggerFactory.getLogger(SendBMail.class);
    final String username = "quinn.admin@88.com";
    final String password = "Y3YYd4hcY2fFB9VY";
    boolean isSSL = true;
    String host = "smtp.88.com";
    int port = 465;
    boolean isAuth = true;
    String from = "quinn.admin@88.com";

    @Resource
    EmailService emailService;

    public boolean sendOneParamMail(EmailType emailType, String param, String email){
        // 可以设计枚举,使用同一个发送邮件的公共方法
        Email register = emailService.getOne(new QueryWrapper<Email>().eq("type",emailType.name()));
        String content = register.getContent().replace(QuinnConstant.EMAIL_REPLACE, param);
        return sendMail(register.getTitle(), content,email);
    }

    public boolean sendParamsMail(EmailType emailType, String email, Map<String,String> map){
        return true;
    }

    private boolean sendMail(String subject,String content,String toEmail){
        Properties props = new Properties();
        props.put("mail.smtp.ssl.enable", isSSL);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", isAuth);
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setSubject(subject);
            message.setContent(content,"text/html;charset=UTF-8");
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            Transport.send(message);
        } catch (Exception e) {
            log.error("发送邮件失败",e);
            return false;
        }
        log.info("发送邮件成功"+toEmail);
        return true;
    }

}
