package com.trade.service.message.impl;

import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import com.trade.service.message.EmailTemplate;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
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 java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @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);;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.name}")
    private String name;

    @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 = "mail" + File.separator + "dynamicTableTemplate";
        return templateEngine.process(path, context);
    }

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

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

    /**
     * 构建 MimeMessageHelper
     * 
     * @param message MimeMessage
     * @param title 主体
     * @param cc 抄送人
     * @param filePath 附件路径
     * @param receiver 接收人
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private MimeMessageHelper structureHelper(MimeMessage message, String title, List<String> cc, String filePath,
            String... receiver) throws MessagingException, UnsupportedEncodingException {
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        // 设置发送者
        helper.setFrom(from, name);
        // 设置收件人
        helper.setTo(receiver);
        if (CollectionUtils.isNotEmpty(cc)) {
            helper.setCc(cc.stream().toArray(String[]::new));
        }
        // 设置主题
        helper.setSubject(title);
        // 附件
        if (StringUtils.isNotEmpty(filePath)) {
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
        }
        return helper;
    }
}
