package com.shzg.project.worn.unit;

import com.alibaba.fastjson2.JSONObject;
import com.shzg.project.worn.domain.MqttSensorDevice;
import com.shzg.project.worn.mapper.MqttSensorDeviceMapper;
import com.shzg.project.worn.service.IMqttSensorDeviceService;
import com.shzg.project.worn.websocket.manager.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 设备离线巡检任务
 * 规则：按设备 report_interval_minute * 3 动态判定离线
 */
@Slf4j
@Component
public class DeviceOfflineCheckTask {

    @Autowired
    private MqttSensorDeviceMapper deviceMapper;

    @Autowired
    private IMqttSensorDeviceService deviceService;

    @Autowired
    private MqttDeviceCache deviceCache;

    @Autowired
    private WebSocketSessionManager sessionManager;

    /**
     * 每5分钟巡检一次
     */
    @Scheduled(initialDelay = 60 * 1000L, fixedDelay = 5 * 60 * 1000L)
    public void checkOfflineDevices() {

        List<MqttSensorDevice> offlineDevices = deviceMapper.selectOfflineDeviceList();

        if (offlineDevices == null || offlineDevices.isEmpty()) {
            return;
        }

        boolean cacheChanged = false;

        for (MqttSensorDevice device : offlineDevices) {

            // ✅ 已经是离线状态，跳过（防止重复更新）
            if ("1".equals(device.getStatus())) {
                continue;
            }

            int rows = deviceService.updateRuntimeStatus(device.getId(), "1");
            if (rows <= 0) {
                continue;
            }

            cacheChanged = true;

            // 推送离线消息
            pushOfflineMessage(device);

            log.info("[DEVICE] 判定离线 deviceId={}, devEui={}, interval={}分钟",
                    device.getId(),
                    device.getDevEui(),
                    device.getReportIntervalMinute());
        }

        // ✅ 只有发生变化才刷新缓存
        if (cacheChanged) {
            deviceCache.refresh();
        }
    }

    /**
     * 推送设备离线消息
     */
    private void pushOfflineMessage(MqttSensorDevice device) {

        if (device == null || device.getDeptId() == null) {
            return;
        }

        JSONObject msg = new JSONObject();
        msg.put("type", "device_offline");
        msg.put("deviceId", device.getId());
        msg.put("devEui", device.getDevEui());
        msg.put("deviceName", device.getDeviceName());
        msg.put("deviceType", device.getDeviceType());
        msg.put("deptId", device.getDeptId());
        msg.put("deptName", device.getDeptName());
        msg.put("deviceStatus", 1);
        msg.put("statusDesc", "离线");
        msg.put("time", System.currentTimeMillis());

        sessionManager.sendToDept(device.getDeptId(), msg.toJSONString());
    }
}