package com.shzg.project.worn.unit;

import com.alibaba.fastjson2.JSONObject;
import com.shzg.project.worn.domain.MqttSensorDevice;
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.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;
        }

        int rows = deviceService.updateRuntimeStatus(device.getId(), "0");
        if (rows <= 0) {
            log.debug("[DEVICE] 收到有效消息但状态未变更, deviceId={}, devEui={}, cachedStatus={}",
                    device.getId(), device.getDevEui(), device.getStatus());
            return;
        }

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

        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());
    }
}
