package com.ruoyi.rocketmq.snmp.config;

import com.ruoyi.rocketmq.domain.RmMonitorPolicy;
import com.ruoyi.rocketmq.service.IRmMonitorPolicyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SwitchStrategyInitializer {

    @Autowired
    private IRmMonitorPolicyService rmMonitorPolicyService;


    // 服务启动时下发默认策略
    @PostConstruct
    public void init() {
        log.info("开始初始化交换机采集策略...");
        try {
            // 下发交换机策略（优先级0和已下发的优先级1）
            List<RmMonitorPolicy> policiesToIssue = new ArrayList<>();

            // 1. 添加优先级为0的默认策略
            RmMonitorPolicy defaultQuery = new RmMonitorPolicy();
            defaultQuery.setPriority("0");
            defaultQuery.setResourceType("switch");
            rmMonitorPolicyService.selectRmMonitorPolicyList(defaultQuery)
                    .stream()
                    .findFirst()
                    .ifPresent(policiesToIssue::add);

            // 2. 添加已下发的优先级1策略
            RmMonitorPolicy issuedQuery = new RmMonitorPolicy();
            issuedQuery.setPriority("1");
            issuedQuery.setStatus("1");
            issuedQuery.setResourceType("switch");
            List<RmMonitorPolicy> monitorPolicies = rmMonitorPolicyService.selectRmMonitorPolicyList(issuedQuery);
            List<RmMonitorPolicy> monitorPolicyList = monitorPolicies.stream()
                    .sorted(Comparator.comparing(RmMonitorPolicy::getCreateTime))
                    .collect(Collectors.toList());
            policiesToIssue.addAll(monitorPolicyList);

            // 3. 统一下发所有符合条件的策略
            policiesToIssue.forEach(policy ->
                    rmMonitorPolicyService.issueSwitchPolicy(policy.getId())
            );
        } catch (Exception e) {
            log.error("初始化交换机采集策略失败", e);
        }
    }

}
