package com.ruoyi.ws;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.ws.config.WebSocketAuthConfigurator;
import com.ruoyi.ws.service.DeviceWebSocketService;

import lombok.extern.slf4j.Slf4j;

/**
 * WebSocket服务类
 */
@ServerEndpoint(value = "/ws/device", configurator = WebSocketAuthConfigurator.class)
@Component
@Slf4j
public class DeviceWebSocket {

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        try {
            String token = (String) config.getUserProperties().get("token");
            String mac = (String) config.getUserProperties().get("mac");
            if (token != null) {
                TokenService tokenService = SpringUtils.getBean(TokenService.class);
                DeviceWebSocketService webSocketService = SpringUtils.getBean(DeviceWebSocketService.class);
                LoginUser loginUser = tokenService.getLoginUser(token);
                tokenService.verifyToken(loginUser);
                if (loginUser != null) {
                    Long userId = loginUser.getUserId();
                    // 添加设备WebSocket会话的MAC地址
                    webSocketService.addMacToSession(mac, session);
                    log.info("用户 {} 连接Mac {} 成功", userId, mac);
                    return;
                }
            }
            session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "未认证"));
        } catch (Exception e) {
            log.error("WebSocket连接异常", e);
        }
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        try {
            DeviceWebSocketService webSocketService = SpringUtils.getBean(DeviceWebSocketService.class);
            webSocketService.removeSession(session);
            log.info("用户{}断开WebSocket连接", session);
        } catch (Exception e) {
            log.error("WebSocket关闭异常", e);
        }
    }

    /**
     * 错误处理
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误", error);
    }
}
