package com.ruoyi.modules.monitor.service;

import java.util.Arrays;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ruoyi.modules.monitor.config.AlarmEmailProperties;

/**
 * 告警邮件服务
 * 
 * @author lydgt
 */
@Service
public class AlarmEmailService
{
    private static final Logger log = LoggerFactory.getLogger(AlarmEmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private AlarmEmailProperties emailProperties;

    @Value("${spring.mail.username}")
    private String fromEmailAddress;

    /**
     * 发送告警邮件
     * 
     * @param subject 邮件主题
     * @param content 邮件内容（HTML格式）
     */
    public void sendAlarmEmail(String subject, String content)
    {
        log.info("准备发送告警邮件 - 主题: {}", subject);
        
        // 检查是否启用邮件告警
        if (!emailProperties.isEnabled())
        {
            log.info("邮件告警功能未启用，跳过发送");
            return;
        }

        // 检查收件人配置
        String recipients = emailProperties.getRecipients();
        if (!StringUtils.hasText(recipients))
        {
            log.warn("收件人列表为空，无法发送告警邮件");
            return;
        }
        
        log.info("邮件配置 - 发件人: {}, 收件人: {}", fromEmailAddress, recipients);

        try
        {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            
            // 设置发件人
            helper.setFrom(fromEmailAddress);
            
            // 设置收件人
            List<String> recipientList = Arrays.asList(recipients.split(","));
            String[] toAddresses = recipientList.stream()
                    .map(String::trim)
                    .filter(StringUtils::hasText)
                    .toArray(String[]::new);
            
            if (toAddresses.length == 0) {
                log.warn("有效的收件人列表为空，无法发送告警邮件");
                return;
            }
            
            helper.setTo(toAddresses);
            
            // 设置主题和内容
            helper.setSubject(subject);
            helper.setText(content, true); // true表示HTML内容
            
            // 发送邮件
            log.info("开始发送邮件...");
            mailSender.send(mimeMessage);
            log.info("告警邮件发送成功 - 主题: {}, 收件人数量: {}", subject, toAddresses.length);
        }
        catch (MessagingException e)
        {
            log.error("发送告警邮件失败 - 主题: {}, 错误信息: {}", subject, e.getMessage(), e);
        }
        catch (Exception e)
        {
            log.error("发送告警邮件时发生未知错误 - 主题: {}, 错误信息: {}", subject, e.getMessage(), e);
        }
    }
}
