package com.aiotagro.cattletrade.job;

import com.aiotagro.cattletrade.business.service.IotDeviceSyncService;
import com.aiotagro.cattletrade.business.service.IotDeviceLogSyncService;
import com.aiotagro.cattletrade.business.service.DeviceWarningService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * IoT设备数据同步定时任务
 *
 * @author System
 * @date 2025-01-16
 */
@Component
public class IotDeviceSyncJob {

    private static final Logger logger = LoggerFactory.getLogger(IotDeviceSyncJob.class);

    @Autowired
    private IotDeviceSyncService iotDeviceSyncService;

    @Autowired
    private IotDeviceLogSyncService iotDeviceLogSyncService;
    
    @Autowired
    private DeviceWarningService deviceWarningService;

    /**
     * 每5分钟同步一次IoT设备数据
     */
    @Scheduled(fixedRate = 5 * 60 * 1000) // 5分钟
    public void syncIotDeviceData() {
        try {
            logger.info("开始执行IoT设备数据同步定时任务");
            iotDeviceSyncService.syncIotDeviceData();
            logger.info("IoT设备数据同步定时任务执行完成");
        } catch (Exception e) {
            logger.error("IoT设备数据同步定时任务执行失败", e);
        }
    }

    /**
     * 每5分钟同步一次设备数据到日志表
     */
    @Scheduled(fixedRate = 5 * 60 * 1000) // 5分钟
    public void syncDeviceDataToLogs() {
        try {
            logger.info("开始执行设备日志同步定时任务");
            iotDeviceLogSyncService.syncDeviceDataToLogs();
            logger.info("设备日志同步定时任务执行完成");
            
            // 输出统计信息
            iotDeviceLogSyncService.logSyncStatistics();
            
            // 执行预警检测
            logger.info("开始执行设备预警检测任务");
            deviceWarningService.checkDeviceWarnings();
            logger.info("设备预警检测任务执行完成");
            
        } catch (Exception e) {
            logger.error("设备日志同步定时任务执行失败", e);
        }
    }
}
