package net.northking.cctp.testbug.api.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.regex.Pattern;

@Service
@RefreshScope
@ConditionalOnMissingBean(name = "EmailServiceImpl")
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSenderImpl javamailsenderimpl;

    @Value("${spring.mail.username}")
    private String from_email;

    private final static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);


    /**
     * 邮件发送(异步)
     *
     * @param title
     * @param content
     * @param receiverEmails 接受人email地址
     * @throws MessagingException
     */
    @Override
    @Async
    public void sendMail(String title, String content, List<String> receiverEmails){
        try {
            MimeMessage mimeMessage = javamailsenderimpl.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from_email);
            helper.setSubject(title);
            helper.setText(content);

            int sendSuccessCount = 0;
            logger.info("邮件地址：===》，{}", javamailsenderimpl.getHost());
            logger.info("发送人：===》，{}", javamailsenderimpl.getUsername());
            logger.info("密码：===》，{}", javamailsenderimpl.getPassword());
            for (String mail : receiverEmails) {
                //正则匹配邮箱格式
                String check = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?.)+[a-zA-Z]{2,}$";
                Pattern compile = Pattern.compile(check);
                if (compile.matcher(mail).matches()) {
                    try {
                        helper.setTo(mail);
                        javamailsenderimpl.send(mimeMessage);
                        logger.info("邮件发送成功");
                    } catch (Exception e) {
                        logger.error("邮件发送失败",e);
                        continue;
                    }
                }
                sendSuccessCount++;
            }
            logger.info("已发送成功：" + sendSuccessCount + " 个邮件，失败：" + (receiverEmails.size() - sendSuccessCount) + " 个邮件");
        } catch (Exception e) {
            logger.error("邮件发送失败",e);
        }
    }
}
