package com.ytpm.monitor.listener;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

@Component
public class NacosServiceDownListener {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${nacos.server-addr}")
    private String nacosServerAddr;

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

    // 可以配置成需要监听的服务名，或者从配置中心动态获取
    private static final String SERVICE_NAME = "your-critical-service"; 

    @PostConstruct
    public void init() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty("serverAddr", nacosServerAddr);
        // 如果Nacos有鉴权，需要设置username和password
        // properties.setProperty("username", "nacos");
        // properties.setProperty("password", "nacos");

        NamingService namingService = NacosFactory.createNamingService(properties);

        // 订阅指定服务，当服务实例列表变化时，会触发eventReceived方法
        namingService.subscribe(SERVICE_NAME, event -> {
            if (event instanceof NamingEvent) {
                NamingEvent namingEvent = (NamingEvent) event;
                List<Instance> currentInstances = namingEvent.getInstances();
                checkAndNotifyServiceChange(SERVICE_NAME, currentInstances);
            }
        });
    }

    private void checkAndNotifyServiceChange(String serviceName, List<Instance> currentInstances) {
        // 这里可以实现更复杂的逻辑，比如与上一次的状态做对比
        // 简单演示：只要实例列表变化就发邮件，并在邮件中写明当前实例数
        int currentSize = currentInstances.size();
        String subject = String.format("[告警] Nacos服务实例变化: %s", serviceName);
        String text = String.format("服务名： %s \n当前存活实例数： %d \n实例列表：\n%s",
                serviceName,
                currentSize,
                currentInstances.stream()
                        .map(instance -> instance.getIp() + ":" + instance.getPort())
                        .collect(Collectors.joining("\n")));

        sendEmail(subject, text);
    }

    private void sendEmail(String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo("devops_team@yourcompany.com"); // 接收告警的邮箱地址
        // message.setCc("manager@yourcompany.com"); // 可以抄送
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }
}