package vip.xiaonuo.coldchain.core.event;

/**
 * @author jackzhou
 * @version 1.0
 * @project jfcloud-coldchain
 * @description 监听传感器数据事件并异步写入 InfluxDB
 * @date 2024/11/12 15:31:43
 */

import com.github.jfcloud.influxdb.service.JfcloudInfluxDBService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import vip.xiaonuo.coldchain.core.alarm.service.check.SensorAlarmChecker;
import vip.xiaonuo.coldchain.core.bean.influxdb.DataType;
import vip.xiaonuo.coldchain.core.bean.influxdb.SensorData;

import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@Component
public class SensorDataEventListener {
    private final JfcloudInfluxDBService jfcloudInfluxDBService;
    private final SensorAlarmChecker sensorAlarmChecker;

    @Async
    @EventListener
    public void handleSensorDataEvent(SensorDataEvent event) {
        SensorData sensorData = event.getSensorData();
        try {
            // 实时数据才预警提醒
            if (Objects.nonNull(sensorData.getType()) && sensorData.getType() == DataType.NEW.getCode()) {
                sensorAlarmChecker.checkAlarm(sensorData);
            }
            jfcloudInfluxDBService.writePojo(sensorData);
//            log.info("成功写入数据到 InfluxDB: {}", sensorData);
        } catch (Exception e) {
            log.error("写入数据到 InfluxDB 时出错: {}", e.getMessage(), e);
        }
    }
}
