package com.erp.task.alert;

import com.erp.task.config.AlertConfig;
import com.erp.task.entity.ScheduledTask;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 告警服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlertService {

    private final AlertConfig alertConfig;
    private final JavaMailSender mailSender;

    private final Map<String, LocalDateTime> silenceCache = new ConcurrentHashMap<>();
    private static final DateTimeFormatter DFT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 发送告警
     */
    @Async("taskExecutor")
    public void sendAlert(ScheduledTask task, String errorMessage) {
        if (!alertConfig.isEnabled()) {
            return;
        }

        // 检查是否在静默期
        if (isInSilencePeriod(task.getId())) {
            log.info("任务告警在静默期，跳过: taskId={}", task.getId());
            return;
        }

        String subject = buildSubject(task);
        String content = buildContent(task, errorMessage);

        // 发送邮件告警
        if (alertConfig.getEmail().isEnabled()) {
            sendEmailAlert(task, subject, content);
        }

        // 发送短信告警
        if (alertConfig.getSms().isEnabled()) {
            sendSmsAlert(task);
        }

        // 发送WebHook告警
        if (alertConfig.getWebhook().isEnabled()) {
            sendWebHookAlert(task, errorMessage);
        }

        // 设置静默期
        silenceCache.put(String.valueOf(task.getId()), LocalDateTime.now());
    }

    /**
     * 发送邮件告警
     */
    private void sendEmailAlert(ScheduledTask task, String subject, String content) {
        try {
            String[] emails = task.getAlertEmails().split(",");
            for (String email : emails) {
                if (email != null && !email.trim().isEmpty()) {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(alertConfig.getEmail().getFrom());
                    message.setTo(email.trim());
                    message.setSubject(subject);
                    message.setText(content);

                    mailSender.send(message);
                    log.info("邮件告警发送成功: to={}, taskId={}", email, task.getId());
                }
            }
        } catch (Exception e) {
            log.error("发送邮件告警失败: taskId={}", task.getId(), e);
        }
    }

    /**
     * 发送短信告警
     */
    private void sendSmsAlert(ScheduledTask task) {
        try {
            String[] phones = task.getAlertPhones().split(",");
            for (String phone : phones) {
                if (phone != null && !phone.trim().isEmpty()) {
                    // 调用短信API（这里简化处理）
                    log.info("短信告警: to={}, taskId={}", phone, task.getId());
                }
            }
        } catch (Exception e) {
            log.error("发送短信告警失败: taskId={}", task.getId(), e);
        }
    }

    /**
     * 发送WebHook告警
     */
    private void sendWebHookAlert(ScheduledTask task, String errorMessage) {
        try {
            // 构建Webhook payload（这里简化处理）
            String payload = String.format(
                    "{\"taskId\":%d,\"taskName\":\"%s\",\"status\":\"FAILED\",\"error\":\"%s\",\"time\":\"%s\"}",
                    task.getId(),
                    task.getTaskName(),
                    errorMessage,
                    LocalDateTime.now().format(DFT));

            log.info("WebHook告警: url={}, payload={}", alertConfig.getWebhook().getUrl(), payload);
        } catch (Exception e) {
            log.error("发送WebHook告警失败: taskId={}", task.getId(), e);
        }
    }

    /**
     * 检查是否在静默期
     */
    private boolean isInSilencePeriod(Long taskId) {
        LocalDateTime lastAlert = silenceCache.get(String.valueOf(taskId));
        if (lastAlert == null) {
            return false;
        }

        long minutes = java.time.Duration.between(lastAlert, LocalDateTime.now()).toMinutes();
        return minutes < alertConfig.getSilenceMinutes();
    }

    /**
     * 构建告警主题
     */
    private String buildSubject(ScheduledTask task) {
        return String.format("[任务告警] %s - %s", task.getTaskName(), task.getTaskGroup());
    }

    /**
     * 构建告警内容
     */
    private String buildContent(ScheduledTask task, String errorMessage) {
        StringBuilder sb = new StringBuilder();
        sb.append("任务执行失败告警\n\n");
        sb.append("任务ID: ").append(task.getId()).append("\n");
        sb.append("任务名称: ").append(task.getTaskName()).append("\n");
        sb.append("任务分组: ").append(task.getTaskGroup()).append("\n");
        sb.append("任务类型: ").append(task.getTaskType()).append("\n");
        sb.append("负责人: ").append(task.getOwner()).append("\n");
        sb.append("Cron表达式: ").append(task.getCronExpression()).append("\n");
        sb.append("错误信息: ").append(errorMessage).append("\n");
        sb.append("告警时间: ").append(LocalDateTime.now().format(DFT)).append("\n\n");
        sb.append("请及时处理！");
        return sb.toString();
    }

    /**
     * 清除静默缓存
     */
    public void clearSilenceCache(Long taskId) {
        silenceCache.remove(String.valueOf(taskId));
    }

    /**
     * 清除所有静默缓存
     */
    public void clearAllSilenceCache() {
        silenceCache.clear();
    }
}
