package com.trade.service.message.impl;

import cn.hutool.core.util.ArrayUtil;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import com.trade.service.message.EmailTemplate;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @description: 发送邮件
 * @Author: wanglang
 * @Date: 2024/3/30 17:00
 * @Version: 1.0
 */
@Component
public class EmailTemplateImpl implements EmailTemplate {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);
    private static final String TEMPLATE_FILE_PATH = "mail" + File.separator;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.name}")
    private String name;
    //联系邮箱
    @Value("${spring.mail.contact}")
    private String contact;

    @Override
    public String getDynamicTableProcess(List<String> headers, List<List<String>> rows) {
        Context context = new Context();
        context.setVariable("headers", headers);
        context.setVariable("rows", rows);
        // Process the template
        String path = TEMPLATE_FILE_PATH + "dynamicTableTemplate";
        return templateEngine.process(path, context);
    }

    @Override
    public boolean sendHtmlMail(String title, String html, String[] cc, String filePath, String[] receiver) {
        try {
            // Create the message
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = structureHelper(message, title, cc, null, receiver);
            structureAttachment(helper, filePath, null);
            helper.setText(html, true);
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            return false;
        }
    }

    @Override
    public boolean sendMailTemplate(String title, String templateName, byte[] attachment, String fileName,
            Map<String, Object> variables, String[] cc, String[] bcc, String[] receiver) {
        variables.put("email", contact);
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = structureHelper(message, title, cc, bcc, receiver);
            // 生成html内容
            Context context = new Context();
            context.setVariables(variables);
            String html = templateEngine.process(TEMPLATE_FILE_PATH + templateName, context);
            helper.setText(html, true);
            // 设置附件
            structureAttachment(helper, attachment, fileName);
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            return false;
        }
    }

    @Override
    public boolean sendSimpleMail(String title, String content, String[] cc, String filePath, String... receiver) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = structureHelper(message, title, cc, null, receiver);
            structureAttachment(helper, filePath, null);
            // 设置内容
            helper.setText(content);
            mailSender.send(message);
            log.info("邮件发送成功");
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            return false;
        }
    }

    @Override
    public boolean sendHtmlMail(String title, String html, String[] cc, String fileName, InputStream in,
            String... receiver) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = structureHelper(message, title, cc, null, receiver);
            structureAttachment(helper, fileName, null);
            // 设置内容
            helper.setText(html, true);
            mailSender.send(message);
            log.info("邮件发送成功");
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            return false;
        }
    }

    /**
     * 构建 MimeMessageHelper
     * 
     * @param message MimeMessage
     * @param title 主体
     * @param cc 抄送人
     * @param receiver 接收人
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private MimeMessageHelper structureHelper(MimeMessage message, String title, String[] cc, String[] bcc,
            String[] receiver) throws MessagingException, UnsupportedEncodingException {
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        // 设置发送者
        helper.setFrom(from, name);
        // 设置收件人
        helper.setTo(receiver);
        if (ArrayUtil.isNotEmpty(cc)) {
            helper.setCc(cc);
        }
        if (ArrayUtil.isNotEmpty(bcc)) {
            helper.setBcc(bcc);
        }
        // 设置主题
        helper.setSubject(title);
        return helper;
    }

    private MimeMessageHelper structureAttachment(MimeMessageHelper helper, String filePath, InputStream in)
            throws MessagingException, UnsupportedEncodingException {
        // 附件
        if (StringUtils.isNotEmpty(filePath) && in == null) {
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
        }
        if (in != null) {
            InputStreamSource inputStreamResource = new InputStreamResource(in);
            helper.addAttachment(filePath, inputStreamResource);
        }
        return helper;
    }

    private MimeMessageHelper structureAttachment(MimeMessageHelper helper, byte[] attachment, String fileName)
            throws MessagingException, UnsupportedEncodingException {
        // 附件
        if (attachment != null) {
            ByteArrayDataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");
            helper.addAttachment(MimeUtility.encodeText(fileName), source);
        }
        return helper;
    }
}
