package com.pnkx.system.service.impl;

import com.pnkx.common.utils.DateUtils;
import com.pnkx.common.utils.StringUtils;
import com.pnkx.system.domain.SysEmail;
import com.pnkx.system.mapper.SysEmailMapper;
import com.pnkx.system.service.ISysEmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author by PHY
 * @Classname SysEmailServiceImpl
 * @date 2021-06-18 09:43
 */
@Service
public class SysEmailServiceImpl implements ISysEmailService {

    @Resource
    private SysEmailMapper sysEmailMapper;
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 查询邮件记录
     *
     * @param id 邮件记录ID
     * @return 邮件记录
     */
    @Override
    public SysEmail selectSysEmailById(Long id) {
        return sysEmailMapper.selectSysEmailById(id);
    }

    /**
     * 查询邮件记录列表
     *
     * @param sysEmail 邮件记录
     * @return 邮件记录
     */
    @Override
    public List<SysEmail> selectSysEmailList(SysEmail sysEmail) {
        return sysEmailMapper.selectSysEmailList(sysEmail);
    }

    /**
     * 修改邮件记录
     *
     * @param sysEmail 邮件记录
     * @return 结果
     */
    @Override
    public int updateSysEmail(SysEmail sysEmail) {
        sysEmail.setUpdateTime(DateUtils.getNowDate());
        return sysEmailMapper.updateSysEmail(sysEmail);
    }

    /**
     * 批量删除邮件记录
     *
     * @param ids 需要删除的邮件记录ID
     * @return 结果
     */
    @Override
    public int deleteSysEmailByIds(Long[] ids) {
        return sysEmailMapper.deleteSysEmailByIds(ids);
    }

    /**
     * 删除邮件记录信息
     *
     * @param id 邮件记录ID
     * @return 结果
     */
    @Override
    public int deleteSysEmailById(Long id) {
        return sysEmailMapper.deleteSysEmailById(id);
    }

    @Override
    @Transactional
    public void sendMail(SysEmail email) throws MessagingException {
        sysEmailMapper.insertSysEmail(email);
        String[] to = validEmail(email.getReceiverEmail());
        if (to != null && to.length > 0) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (StringUtils.isNotEmpty(email.getCcEmail())) {
                helper.setCc(Objects.requireNonNull(validEmail(email.getCcEmail())));
            }
            helper.setSubject(email.getSubject());
            helper.setText(email.getContent(), true);
            javaMailSender.send(message);
        }
    }

    private String[] validEmail(String emails) {
        if (StringUtils.isNotBlank(emails)) {
            return Arrays.stream(emails.split(","))
                    .filter(this::isEmail)
                    .distinct()
                    .toArray(String[]::new);
        }
        return null;
    }

    private Boolean isEmail(String email) {
        String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return Pattern.compile(regEx1).matcher(email.trim()).matches();
    }

    private static String getInvalidAddresses(Throwable e) {
        if (e == null) {
            return null;
        }
        if (e instanceof MailSendException) {
            for (Exception exception : ((MailSendException) e).getMessageExceptions()) {
                if (exception instanceof SendFailedException) {
                    return getStringAddress(((SendFailedException) exception).getInvalidAddresses());
                }
            }
        }
        if (e instanceof SendFailedException) {
            return getStringAddress(((SendFailedException) e).getInvalidAddresses());
        }
        return null;
    }

    private static String getStringAddress(Address[] address) {
        List<String> invalid = new ArrayList<>();
        for (Address a : address) {
            String aa = ((InternetAddress) a).getAddress();
            if (!StringUtils.isEmpty(aa)) {
                invalid.add(aa);
            }
        }
        return invalid.stream().distinct().collect(Collectors.joining(","));
    }
}
