package org.xyzh.message.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.xyzh.message.config.EmailConfigProperties;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

/**
 * @description 邮件发送工具类
 * @filename EmailUtils.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-11-03
 */
@Component
@ConditionalOnBean(JavaMailSender.class)
public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private EmailConfigProperties emailConfigProperties;

    /**
     * 发送简单文本邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @return 是否发送成功
     */
    public boolean sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            String from = emailConfigProperties.getUsername();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            logger.info("简单邮件发送成功，收件人: {}", to);
            return true;
        } catch (Exception e) {
            logger.error("简单邮件发送失败，收件人: {}, 错误: {}", to, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送HTML格式邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content HTML格式的邮件内容
     * @return 是否发送成功
     */
    public boolean sendHtmlEmail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            String from = emailConfigProperties.getUsername();
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // true表示HTML格式
            
            mailSender.send(message);
            logger.info("HTML邮件发送成功，收件人: {}", to);
            return true;
        } catch (MessagingException e) {
            logger.error("HTML邮件发送失败，收件人: {}, 错误: {}", to, e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送验证码邮件
     * @param to 收件人邮箱
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String to, String code) {
        String subject = "【红色思政学习平台】邮箱验证码";
        String content = buildVerificationCodeHtml(code);
        return sendHtmlEmail(to, subject, content);
    }

    /**
     * 构建验证码邮件的HTML内容
     * @param code 验证码
     * @return HTML内容
     */
    private String buildVerificationCodeHtml(String code) {
        return "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<style>" +
                "body { font-family: 'Microsoft YaHei', Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 20px; }" +
                ".container { max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }" +
                ".header { background: linear-gradient(135deg, #C62828 0%, #E53935 100%); padding: 30px; text-align: center; }" +
                ".header h1 { color: #ffffff; margin: 0; font-size: 24px; }" +
                ".content { padding: 40px 30px; }" +
                ".content p { color: #333333; line-height: 1.8; margin: 10px 0; }" +
                ".code-box { background-color: #f8f9fa; border-left: 4px solid #C62828; padding: 20px; margin: 20px 0; text-align: center; }" +
                ".code { font-size: 32px; font-weight: bold; color: #C62828; letter-spacing: 5px; font-family: 'Courier New', monospace; }" +
                ".tips { color: #666666; font-size: 14px; margin-top: 20px; line-height: 1.6; }" +
                ".footer { background-color: #f8f9fa; padding: 20px; text-align: center; color: #999999; font-size: 12px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<div class=\"container\">" +
                "<div class=\"header\">" +
                "<h1>红色思政学习平台</h1>" +
                "</div>" +
                "<div class=\"content\">" +
                "<p>尊敬的用户，您好！</p>" +
                "<p>您正在进行邮箱验证，您的验证码为：</p>" +
                "<div class=\"code-box\">" +
                "<div class=\"code\">" + code + "</div>" +
                "</div>" +
                "<div class=\"tips\">" +
                "<p>• 验证码有效期为10分钟，请尽快完成验证</p>" +
                "<p>• 如果这不是您的操作，请忽略此邮件</p>" +
                "<p>• 为了保护您的账号安全，请勿将验证码告知他人</p>" +
                "</div>" +
                "</div>" +
                "<div class=\"footer\">" +
                "<p>此邮件由系统自动发送，请勿回复</p>" +
                "<p>Copyright © 红色思政智能体平台</p>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }

    /**
     * 生成6位数字验证码
     * @return 验证码
     */
    public static String generateVerificationCode() {
        return String.valueOf((int)((Math.random() * 9 + 1) * 100000));
    }
}

