package com.bonus.system.warning;

import com.alibaba.fastjson.JSON;
import com.bonus.common.core.utils.SpringUtils;
import com.bonus.system.service.ISysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
    private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    public static void closeSession(WebSocketSession session) throws IOException {
        session.close();
    }

    /**
     *
     * @event 监听异常日志，推送到前端
     */
    @EventListener
    public void onLogSaved(WaringLogEvent event) {
        try {
            SysWarning warning = event.getSysWarning();
            String jsonStr = JSON.toJSONString(warning);
            sendMessageToAll(jsonStr);
        } catch (Exception e) {
            logger.error("处理日志告警失败" + event);
        }
    }

    /**
     *
     * @event 监听socket连接
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        logger.debug("WebSocket 连接建立，Session ID: " + headerAccessor.getSessionId());
    }

    /**
     *
     * @event 监听socket断开连接
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        logger.debug("WebSocket 连接断开，Session ID: " + headerAccessor.getSessionId());
    }

    // 处理用户确认消息
    @MessageMapping("/alert-handled")
    public void handleAlert(String alertId) {
        // 在这里处理告警确认逻辑
        logger.debug("Alert " + alertId + " has been handled");

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        logger.debug("WebSocket 连接成功: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        logger.debug("接收到消息: " + payload);

        ISysLogService logService = SpringUtils.getBean(ISysLogService.class);
        logService.updateLogsWithHandledStatus(payload);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        logger.debug("WebSocket 连接关闭: " + session.getId());
    }

    public void sendMessageToAll(String message) throws Exception {
        for (WebSocketSession session : sessions) {
            session.sendMessage(new TextMessage(message));
        }
    }
}
