package com.jay.monitor.data.server.report;

import com.jay.monitor.data.core.model.serializable.base.BaseDTO;
import com.jay.monitor.data.server.enums.AlertRuleEnums;
import com.jay.monitor.data.server.models.dto.alert.RealTimeAlert;
import com.jay.monitor.data.server.report.alert.notify.AlertRealTimeMsg;
import com.jay.monitor.data.server.report.alert.rule.AlertRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Module 告警模块
 * @Description 实时告警模块
 * @Author liukaixiong
 * @Date 2021/1/14 10:35
 */
@Component
public class RealtimeAlertProcess {

    @Autowired(required = false)
    private List<AlertRule> alertRules;

    @Autowired(required = false)
    private List<AlertRealTimeMsg> realTimeMsgProcesses;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 批量数据验证
     *
     * @param baseDTOList
     */
    public void process(List<? extends BaseDTO> baseDTOList) {

        if (this.alertRules == null || this.alertRules.size() == 0) {
            logger.debug("没有对应的匹配规则");
            return;
        }


        for (int i = 0; i < baseDTOList.size(); i++) {
            BaseDTO baseDTO = baseDTOList.get(i);
            for (int j = 0; j < this.alertRules.size(); j++) {
                // 进行规则验证
                AlertRule alertRule = this.alertRules.get(j);
                if (alertRule.isTrigger(baseDTO)) {
                    RealTimeAlert realTimeAlert = new RealTimeAlert();
                    AlertRuleEnums alertRuleEnums = alertRule.ruleType();
                    BeanUtils.copyProperties(baseDTO, realTimeAlert);
                    realTimeAlert.setTriggerType(alertRuleEnums);
                    // 实时告警处理器
                    if (this.realTimeMsgProcesses != null) {
                        this.realTimeMsgProcesses.forEach((alert) -> {
                            if (!alert.isSkipAlert(realTimeAlert)) {
                                logger.debug("[[[[[[[[触发告警]]]]]]]]");
                                alert.send(alertRuleEnums, realTimeAlert);
                            } else {
                                logger.debug("该项目处于告警休眠期，不告警。");
                            }
                        });
                    }
                    break;
                }
            }
        }
    }

}
