package com.haha.admin.task;

import com.haha.common.constant.DeviceConstants;
import com.haha.entity.Device;
import com.haha.sdk.HahaClient;
import com.haha.sdk.model.DeviceOnlineStatus;
import com.haha.service.DeviceAlertService;
import com.haha.service.DeviceService;
import com.haha.service.config.DeviceAlertProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceMonitorTask {

    private final DeviceService deviceService;
    private final DeviceAlertService deviceAlertService;
    private final DeviceAlertProperties alertProperties;
    private final HahaClient hahaClient;

    /**
     * 定时巡检设备在线状态
     * 定时扫描，间隔由配置 device.alert.scan-interval-minutes 控制，默认5分钟
     */
    @Scheduled(fixedDelayString = "#{${device.alert.scan-interval-minutes:5} * 60 * 1000}")
    public void scanDeviceOnlineStatus() {
        if (!alertProperties.isEnabled()) {
            return;
        }

        log.info("[设备巡检] 开始执行设备在线状态巡检...");
        long startTime = System.currentTimeMillis();
        int totalChecked = 0;
        int offlineCount = 0;

        try {
            // 1. 查询所有状态为正常(status=1)的设备
            List<Device> devices = deviceService.lambdaQuery()
                    .eq(Device::getStatus, DeviceConstants.STATUS_ONLINE)
                    .list();

            if (devices.isEmpty()) {
                log.info("[设备巡检] 无需巡检的设备");
                return;
            }

            log.info("[设备巡检] 待巡检设备数量: {}", devices.size());

            // 2. 分批处理，每批50台
            int batchSize = 50;
            for (int i = 0; i < devices.size(); i += batchSize) {
                List<Device> batch = devices.subList(i, Math.min(i + batchSize, devices.size()));

                for (Device device : batch) {
                    try {
                        // 调用SDK查询在线状态
                        DeviceOnlineStatus onlineStatus = hahaClient.getDeviceApi().getOnlineStatus(device.getDeviceId());
                        totalChecked++;

                        if (onlineStatus != null && onlineStatus.getIsOnline() != null && onlineStatus.getIsOnline() == com.haha.common.enums.DeviceOnlineStatus.OFFLINE.getCode()) {
                            // 设备离线
                            offlineCount++;
                            deviceAlertService.processOfflineAlert(device.getDeviceId(), "SCHEDULED_SCAN");
                        } else if (onlineStatus != null && onlineStatus.getIsOnline() != null && onlineStatus.getIsOnline() == com.haha.common.enums.DeviceOnlineStatus.ONLINE.getCode()) {
                            // 设备在线，检查是否需要发恢复通知
                            deviceAlertService.processBackOnlineNotify(device.getDeviceId());
                        }

                        // 限流：每次API调用间隔200ms
                        Thread.sleep(200);

                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.warn("[设备巡检] 巡检任务被中断");
                        return;
                    } catch (Exception e) {
                        log.warn("[设备巡检] 查询设备 {} 在线状态失败: {}", device.getDeviceId(), e.getMessage());
                    }
                }
            }

        } catch (Exception e) {
            log.error("[设备巡检] 巡检任务执行异常", e);
        }

        long costTime = System.currentTimeMillis() - startTime;
        log.info("[设备巡检] 巡检完成，共检查 {} 台设备，发现 {} 台离线，耗时 {}ms",
                totalChecked, offlineCount, costTime);
    }
}
