package com.kym.admin.jobs;

import com.kym.entity.WashDevice;
import com.kym.service.DeviceHealthProbeService;
import com.kym.service.WashDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 设备健康探测定时任务
 * 主动查询故障状态设备的连通性，探测到设备在线则触发自动恢复
 *
 * @author skyline
 */
@Slf4j
@Component
public class DeviceHealthProbeJob {

    private final WashDeviceService washDeviceService;
    private final DeviceHealthProbeService deviceHealthProbeService;

    public DeviceHealthProbeJob(WashDeviceService washDeviceService,
                                DeviceHealthProbeService deviceHealthProbeService) {
        this.washDeviceService = washDeviceService;
        this.deviceHealthProbeService = deviceHealthProbeService;
    }

    /**
     * 每3分钟扫描所有故障状态设备，主动探测连通性
     */
    @Async("AsyncExecutor")
    @Scheduled(cron = "0 */3 * * * ?")
    public void probeFaultDevices() {
        log.debug("设备健康探测-开始");
        List<WashDevice> faultDevices = washDeviceService.lambdaQuery()
                .eq(WashDevice::getState, WashDevice.STATE_故障)
                .list();

        if (faultDevices.isEmpty()) {
            log.debug("设备健康探测-无故障设备");
            return;
        }

        log.info("设备健康探测-发现 {} 个故障设备，开始探测", faultDevices.size());
        int recovered = 0;

        for (WashDevice device : faultDevices) {
            try {
                if (deviceHealthProbeService.probeAndRecover(device)) {
                    recovered++;
                }
            } catch (Exception e) {
                log.error("设备健康探测-设备 {} 探测异常", device.getDeviceName(), e);
            }
        }

        log.info("设备健康探测-结束，共探测 {} 个故障设备，恢复 {} 个", faultDevices.size(), recovered);
    }
}
