package com.ruoyi.oa.utils;

import com.ruoyi.oa.domain.OaEmailAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import com.ruoyi.oa.config.DynamicMailConfig;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * 邮件发送工具类
 * 
 * @author ruoyi
 */
@Component
public class EmailUtil {
    
    @Autowired
    private JavaMailSender javaMailSender;
    
    @Autowired
    private DynamicMailConfig dynamicMailConfig;
    
    /**
     * 发送纯文本邮件
     *
     * @param from    发件人邮箱
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param text    纯文本内容
     */
    public void sendMail(String from, String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }
    
    /**
     * 使用动态配置发送纯文本邮件
     *
     * @param account 邮箱账号信息
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param text    纯文本内容
     */
    public void sendMailWithDynamicConfig(OaEmailAccount account, String to, String subject, String text) {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(account.getEmail());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        dynamicMailSender.send(message);
    }
    
    /**
     * 发送纯文本邮件（批量）
     *
     * @param from    发件人邮箱
     * @param toList  收件人邮箱列表
     * @param subject 邮件主题
     * @param text    纯文本内容
     */
    public void sendMailBatch(String from, List<String> toList, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(toList.toArray(new String[0]));
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }
    
    /**
     * 发送富文本邮件
     *
     * @param from    发件人邮箱
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param htmlContent HTML内容
     */
    public void sendHtmlMail(String from, String to, String subject, String htmlContent) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true); // 第二个参数true表示这是HTML内容
        javaMailSender.send(mimeMessage);
    }
    
    /**
     * 使用动态配置发送富文本邮件
     *
     * @param account     邮箱账号信息
     * @param to          收件人邮箱
     * @param subject     邮件主题
     * @param htmlContent HTML内容
     */
    public void sendHtmlMailWithDynamicConfig(com.ruoyi.oa.domain.OaEmailAccount account, String to, String subject, String htmlContent) throws MessagingException {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        MimeMessage mimeMessage = dynamicMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(account.getEmail());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        dynamicMailSender.send(mimeMessage);
    }
    
    /**
     * 发送富文本邮件（批量）
     *
     * @param from    发件人邮箱
     * @param toList  收件人邮箱列表
     * @param subject 邮件主题
     * @param htmlContent HTML内容
     */
    public void sendHtmlMailBatch(String from, List<String> toList, String subject, String htmlContent) throws MessagingException {
        for (String to : toList) {
            sendHtmlMail(from, to, subject, htmlContent);
        }
    }
    
    /**
     * 发送带附件的邮件
     *
     * @param from      发件人邮箱
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param text      邮件内容
     * @param filePath  附件文件路径
     */
    public void sendMailWithAttachment(String from, String to, String subject, String text, String filePath) throws MessagingException {
        File attachment = new File(filePath);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);
        helper.addAttachment(attachment.getName(), attachment);
        javaMailSender.send(mimeMessage);
    }
    
    /**
     * 使用动态配置发送带附件的邮件
     *
     * @param account   邮箱账号信息
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param text      邮件内容
     * @param filePath  附件文件路径
     */
    public void sendMailWithAttachmentAndDynamicConfig(com.ruoyi.oa.domain.OaEmailAccount account, String to, String subject, String text, String filePath) throws MessagingException {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        File attachment = new File(filePath);
        MimeMessage mimeMessage = dynamicMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(account.getEmail());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);
        helper.addAttachment(attachment.getName(), attachment);
        dynamicMailSender.send(mimeMessage);
    }
    
    /**
     * 发送带附件的富文本邮件
     *
     * @param from      发件人邮箱
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param htmlContent HTML内容
     * @param filePath  附件文件路径
     */
    public void sendHtmlMailWithAttachment(String from, String to, String subject, String htmlContent, String filePath) throws MessagingException {
        File attachment = new File(filePath);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        helper.addAttachment(attachment.getName(), attachment);
        javaMailSender.send(mimeMessage);
    }
    
    /**
     * 使用动态配置发送带附件的富文本邮件
     *
     * @param account     邮箱账号信息
     * @param to          收件人邮箱
     * @param subject     邮件主题
     * @param htmlContent HTML内容
     * @param filePath    附件文件路径
     */
    public void sendHtmlMailWithAttachmentAndDynamicConfig(com.ruoyi.oa.domain.OaEmailAccount account, String to, String subject, String htmlContent, String filePath) throws MessagingException {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        File attachment = new File(filePath);
        MimeMessage mimeMessage = dynamicMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(account.getEmail());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        helper.addAttachment(attachment.getName(), attachment);
        dynamicMailSender.send(mimeMessage);
    }
    
    /**
     * 发送带多个附件的邮件
     *
     * @param from      发件人邮箱
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param htmlContent HTML内容
     * @param filePaths 附件文件路径列表
     */
    public void sendHtmlMailWithAttachments(String from, String to, String subject, String htmlContent, List<String> filePaths) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        
        for (String filePath : filePaths) {
            File attachment = new File(filePath);
            if (attachment.exists()) {
                helper.addAttachment(attachment.getName(), attachment);
            }
        }
        
        javaMailSender.send(mimeMessage);
    }
    
    /**
     * 使用动态配置发送带多个附件的邮件
     *
     * @param account     邮箱账号信息
     * @param to          收件人邮箱
     * @param subject     邮件主题
     * @param htmlContent HTML内容
     * @param filePaths   附件文件路径列表
     */
    public void sendHtmlMailWithAttachmentsAndDynamicConfig(com.ruoyi.oa.domain.OaEmailAccount account, String to, String subject, String htmlContent, List<String> filePaths) throws MessagingException {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        MimeMessage mimeMessage = dynamicMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(account.getEmail());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        
        for (String filePath : filePaths) {
            File attachment = new File(filePath);
            if (attachment.exists()) {
                helper.addAttachment(attachment.getName(), attachment);
            }
        }
        
        dynamicMailSender.send(mimeMessage);
    }
    
    /**
     * 发送带内嵌图片的邮件
     *
     * @param from      发件人邮箱
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param htmlContent HTML内容（包含cid:xxx的图片引用）
     * @param imagePaths 内嵌图片路径列表
     */
    public void sendHtmlMailWithInlineImages(String from, String to, String subject, String htmlContent, List<String> imagePaths) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        
        for (int i = 0; i < imagePaths.size(); i++) {
            String imagePath = imagePaths.get(i);
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                String cid = "image" + i;
                helper.addInline(cid, imageFile);
            }
        }
        
        javaMailSender.send(mimeMessage);
    }
    
    /**
     * 使用动态配置发送带内嵌图片的邮件
     *
     * @param account     邮箱账号信息
     * @param to          收件人邮箱
     * @param subject     邮件主题
     * @param htmlContent HTML内容（包含cid:xxx的图片引用）
     * @param imagePaths  内嵌图片路径列表
     */
    public void sendHtmlMailWithInlineImagesAndDynamicConfig(OaEmailAccount account, String to, String subject, String htmlContent, List<String> imagePaths) throws MessagingException {
        JavaMailSender dynamicMailSender = dynamicMailConfig.createMailSender(account);
        MimeMessage mimeMessage = dynamicMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(account.getEmail());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        
        for (int i = 0; i < imagePaths.size(); i++) {
            String imagePath = imagePaths.get(i);
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                String cid = "image" + i;
                helper.addInline(cid, imageFile);
            }
        }
        
        dynamicMailSender.send(mimeMessage);
    }
    
    /**
     * 处理HTML内容中的图片，将外链图片转为内嵌
     *
     * @param htmlContent 原始HTML内容
     * @param imagePaths  图片路径列表
     * @return 处理后的HTML内容
     */
    public String processHtmlWithInlineImages(String htmlContent, List<String> imagePaths) {
        if (imagePaths == null || imagePaths.isEmpty()) {
            return htmlContent;
        }
        
        String processedHtml = htmlContent;
        for (int i = 0; i < imagePaths.size(); i++) {
            String imagePath = imagePaths.get(i);
            String cid = "image" + i;
            // 这里可以根据需要替换图片URL为cid引用
            // 例如：将 <img src="path/to/image.jpg"> 替换为 <img src="cid:image0">
            processedHtml = processedHtml.replace("image" + i + ".jpg", "cid:" + cid);
            processedHtml = processedHtml.replace("image" + i + ".png", "cid:" + cid);
        }
        
        return processedHtml;
    }

    /**
     * 下载网络文件到本地临时文件，保留原始文件后缀
     * @param url 文件的http/https链接
     * @return 本地临时文件
     */
    public static File downloadUrlToTempFile(String url) throws Exception {
        // 提取文件名和后缀
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        String suffix = "";
        int dotIdx = fileName.lastIndexOf('.');
        if (dotIdx != -1) {
            suffix = fileName.substring(dotIdx);
        }
        File tempFile = File.createTempFile("mail_attach_", suffix);
        try (java.io.InputStream in = new java.net.URL(url).openStream();
             java.io.OutputStream out = new java.io.FileOutputStream(tempFile)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    }
} 