package com.liquidnet.service.adam.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.liquidnet.service.adam.common.AdamErrorCode;
import com.liquidnet.service.adam.common.EmailEntity;
import com.liquidnet.service.adam.dto.base.AdamResultDto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Data
public class EmailUtil {

    //发件邮箱
    private String myEmailAccount;

    //邮箱密码
    private String myEmailPassword;

    //smtp地址
    private String myEmailSMTPHost;

    private Transport transport;

    private Session session;

    private Properties props;

    public void doSendMsg(EmailEntity emailEntity) throws Exception {
        if (StringUtils.isBlank(emailEntity.getTargetMail())) {
            throw new RuntimeException("收件人邮箱不能为空");
        }
        session = Session.getDefaultInstance(props);
        session.setDebug(true);
        MimeMessage message = createMimeMessage(session, myEmailAccount, emailEntity);
        transport = session.getTransport();
        transport.connect(myEmailAccount, myEmailPassword);

        try {
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {

            log.error(e.getMessage(), e);
        } finally {
            // 7. 关闭连接
            transport.close();
        }

    }

    public static MimeMessage createMimeMessage(Session session, String sendMail, EmailEntity emailEntity) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, emailEntity.getFromPerson(), "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(emailEntity.getTargetMail(), emailEntity.getToPerson(), "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject(emailEntity.getSubject(), "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(emailEntity.getContent(), "text/html;charset=UTF-8");

        // 6. 设置发件时间 (立即发送)
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

    // 校验邮箱格式

    /**
     * 校验邮箱格式
     * @param email 邮箱
     */
    public static AdamResultDto checkEmailFormat( String email) {
        String reg = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        Pattern r = Pattern.compile(reg);
        Matcher m = r.matcher(email);
        if (!m.matches()) {
            return AdamResultDto.failure(AdamErrorCode.EMAIL_FORMAT_INVALID);
        }
        return AdamResultDto.success();
    }

}
