package com.zehong.system.service.websocket;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zehong.system.domain.TEquipmentInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
 * @author lenovo
 * @date 2025/8/14
 * @description 老化柜WebSocket处理器
 */
@Component
public class AgingCabinetWebSocketHandler extends TextWebSocketHandler {

    // 线程安全的会话列表，存储所有连接的客户端
    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
    private static final Logger log = LoggerFactory.getLogger(AgingCabinetWebSocketHandler.class);

    /**
     * 连接建立后添加会话
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        log.info("新的老化柜WebSocket连接建立，当前连接数: {}", sessions.size());
    }

    /**
     * 连接关闭后移除会话
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
        log.info("老化柜WebSocket连接关闭，当前连接数: {}", sessions.size());
    }

    /**
     * 广播老化柜数据给所有客户端
     * @param equipmentList 处理后的老化柜设备列表
     */
    public void broadcastAgingCabinetData(List<TEquipmentInfo> equipmentList) {
        try {
            String message = createAgingCabinetMessage(equipmentList);
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(message));
                }
            }
        } catch (IOException e) {
            log.error("广播老化柜数据失败", e);
        }
    }

    /**
     * 构建老化柜数据消息
     * 转换为前端需要的格式（与cabinetRows所需字段匹配）
     */
    private String createAgingCabinetMessage(List<TEquipmentInfo> equipmentList) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> cabinetData = new ArrayList<>();

        for (TEquipmentInfo equipment : equipmentList) {
            Map<String, Object> dataMap = new HashMap<>();
            // 前端需要的核心字段
            dataMap.put("fEquipmentId", equipment.getfEquipmentId());
            dataMap.put("fEquipmentCode", equipment.getfEquipmentCode());
            dataMap.put("fStatus", equipment.getfStatus());
            dataMap.put("errorReason", equipment.getErrorReason());
            dataMap.put("registerValues", equipment.getRegisterValues()); // 可选：层状态数据
            cabinetData.add(dataMap);
        }

        Map<String, Object> message = new HashMap<>();
        message.put("type", "aging_cabinet_data"); // 消息类型标识
        message.put("data", cabinetData);
        return mapper.writeValueAsString(message);
    }
}