package com.shzg.project.worn.unit;

import com.alibaba.fastjson2.JSONObject;
import com.shzg.common.utils.DateUtils;
import com.shzg.project.worn.domain.MqttSensorDevice;
import com.shzg.project.worn.service.IMqttSensorDeviceService;
import com.shzg.project.worn.unit.MqttDeviceCache;
import com.shzg.project.worn.websocket.manager.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 设备状态工具类（在线 / 离线统一处理）
 */
@Slf4j
@Component
public class DeviceStatusUtil {

    @Autowired
    private IMqttSensorDeviceService deviceService;

    @Autowired
    private WebSocketSessionManager sessionManager;

    @Autowired
    private MqttDeviceCache deviceCache;

    /**
     * 🔥 设备恢复在线（只在“有效消息”后调用）
     */
    public void handleOnline(MqttSensorDevice device) {

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

        // ✅ 已经在线，直接返回
        if ("0".equals(device.getStatus())) {
            return;
        }

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

        log.info("[DEVICE] 恢复在线 deviceId={}, devEui={}",
                device.getId(), device.getDevEui());

        // 推送WebSocket
        pushOnlineMessage(device);

        // 刷新缓存
        deviceCache.refresh();
    }

    /**
     * 推送在线消息
     */
    private void pushOnlineMessage(MqttSensorDevice device) {

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

        JSONObject msg = new JSONObject();
        msg.put("type", "device_online");
        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", 0);
        msg.put("statusDesc", "在线");
        msg.put("time", System.currentTimeMillis());

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