package com.sckw.slope.detection.utils;

/**
 * @author lfdc
 * @description
 * @date 2023-12-08 08:12:53
 */

import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;

import java.io.*;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 发送邮件工具类
 */
@Slf4j
@ComponentScan
public class MailUtil {

    public static String buildContent(HashMap<String,String> parameterMap) throws IOException {
        String reminderDate = parameterMap.get("reminderDate");
        //加载邮件html模板
        File fileName = new File("Email.html");
        BufferedReader fileReader = new BufferedReader(new FileReader(fileName));

        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.error("读取文件失败，fileName:{}", fileName, e);
        } finally {
            fileReader.close();
        }

        Date date = new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String array[] = {"梅奥心磁","100",sdf.format(date),"serverId"};

        //替换参数
        String htmlText = MessageFormat.format(buffer.toString(), array);
        return htmlText;
    }

    /**
     * 邮件发送
     * @param mailHost 邮件服务地址
     * @param fromMail 发件人
     * @param fromName 发件人名
     * @param fromMailPwd 发件人密码
     * @param toMails 收件人，多个用英文逗号分隔
     * @param mailTitle 邮件标题
     * @param mailContent 邮件内容
     * @throws Exception
     */
    public static void sendMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
                                String toMails, String mailTitle, String mailContent) throws Exception {
        String[] toMailArr = null;
        if (toMails != null && !toMails.equals("")) {
            toMailArr = toMails.split(",");
        } else {
            throw new Exception("邮件发送人不能为空");
        }

        // 邮件属性信息
        Properties props = new Properties();
        props.put("mail.host", mailHost);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
        //session.setDebug(true); // 是否打印调试信息
        toMailArr = toMails.split(",");
        for (String to : toMailArr) {
            MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
            message.setFrom(new InternetAddress(fromMail));// 设置发件人的地址
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 设置收件人,并设置其接收类型为TO
            message.setSubject(mailTitle);// 设置标题
            message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
            message.setSentDate(new Date());// 设置发信时间
            message.saveChanges();// 存储邮件信息

            // 发送邮件
            Transport transport = session.getTransport();
            transport.connect(fromMail, fromMailPwd);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
    }

    /**
     * 邮件发送（群发）
     * @param mailHost 邮件服务地址
     * @param fromMail 发件人
     * @param fromName 发件人名
     * @param fromMailPwd 发件人密码
     * @param toMails 收件人，多个用英文逗号分隔
     * @param mailTitle 邮件标题
     * @param mailContent 邮件内容
     * @throws Exception
     */
    public static void sendGroupMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
                                     String toMails, String mailTitle, String mailContent) throws Exception {
        String[] toMailArr = null;
        if (toMails != null && !toMails.equals("")) {
            toMailArr = toMails.split(",");
        } else {
            throw new Exception("邮件发送人不能为空");
        }

        // 邮件属性信息
        Properties props = new Properties();
        props.put("mail.host", mailHost);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");


        Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
        //session.setDebug(true); // 是否打印调试信息
        MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
        message.setFrom(new InternetAddress(fromMail)); // 设置发件人的地址
        InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
        for (int i = 0; i < toMailArr.length; i++) {
            sendTo[i] = new InternetAddress(toMailArr[i], fromName);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo); // 设置收件人,并设置其接收类型为TO
        message.setSubject(mailTitle); // 设置标题
        message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
        message.setSentDate(new Date()); // 设置发信时间
        message.saveChanges(); // 存储邮件信息

        // 发送邮件
        Transport transport = session.getTransport();
        transport.connect(fromMail, fromMailPwd);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 读取html文件为String
     * @param htmlFileName
     * @return
     * @throws Exception
     */
    public static String readHtmlToString(String htmlFileName) throws Exception{
        InputStream is = null;
        Reader reader = null;
        try {
            is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
            if (is ==  null) {
                throw new Exception("未找到模板文件");
            }
            reader = new InputStreamReader(is, "UTF-8");
            StringBuilder sb = new StringBuilder();
            int bufferSize = 1024;
            char[] buffer = new char[bufferSize];
            int length = 0;
            while ((length = reader.read(buffer, 0, bufferSize)) != -1){
                sb.append(buffer, 0, length);
            }
            return sb.toString();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("关闭io流异常", e);
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch ( IOException e) {
                log.error("关闭io流异常", e);
            }
        }
    }
    public static String readFile(String filePath) {
        StringBuilder content = new StringBuilder();
        File fileName = new File(filePath);
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

    /**
     *  读取本地html文件里的html代码
     * @return
     */
    public static String toHtmlString(String filePath) {
        File file = new File(filePath);
        // 获取HTML文件流
        StringBuffer htmlSb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), "UTF-8"));
            while (br.ready()) {
                htmlSb.append(br.readLine());
            }
            br.close();
            // 删除临时文件
            //file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // HTML文件字符串
        String htmlStr = htmlSb.toString();
        // 返回经过清洁的html文本
        return htmlStr;
    }

    public static String readResourceFile(String filePath) throws IOException {
//        ClassLoader classLoader = MailUtil.class.getClassLoader();
//        File file = new File(classLoader.getResource(filePath).getFile());
        File file = new File(filePath);
//        Document document = Jsoup.parse(file, "UTF-8");
        StringBuilder content = new StringBuilder();
//        InputStream inputStream = MailUtil.class.getClassLoader().getResourceAsStream(filePath);
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

    /**
     * 将修改后的内容写回HTML文件
     * @param filePath
     * @param content
     */
    public static void writeFile(String filePath, String content) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
            bw.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String replacePlaceholders(String template, Map<String, String> valueMap) {
        // 遍历Map，替换模板中的占位符
        for (Map.Entry<String, String> entry : valueMap.entrySet()) {
            String placeholder = "{" + entry.getKey() + "}";
            String replacement = entry.getValue();
            template = template.replace(placeholder, replacement);
        }
        return template;
    }
}
