package com.zehong.system.service.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zehong.system.domain.RobotArmCommand;
import com.zehong.system.service.IRobotArmCommandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
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 javax.annotation.Resource;
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/4
 * @description websocketHandler
 */
@Component
public class RobotArmWebSocketHandler extends TextWebSocketHandler {

    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    private static final Logger log = LoggerFactory.getLogger(RobotArmWebSocketHandler.class);
    @Resource
    private IRobotArmCommandService robotArmCommandService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        sendInitialData(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        // 处理客户端请求
        if ("{\"type\":\"request\",\"commands\":[\"loading\",\"unloading\"]}".equals(payload)) {
            sendInitialData(session);
        }
    }

    private void sendInitialData(WebSocketSession session) throws IOException {
        // 发送待上料指令
        List<RobotArmCommand> loadingCommands = robotArmCommandService.findByType("0");
        session.sendMessage(new TextMessage(createMessage("loading", loadingCommands)));

        // 发送待下料指令
        List<RobotArmCommand> unloadingCommands = robotArmCommandService.findByType("1");
        session.sendMessage(new TextMessage(createMessage("unloading", unloadingCommands)));
    }

    private String createMessage(String type, List<RobotArmCommand> commands) {
        ObjectMapper mapper = new ObjectMapper();
        try {

            // 创建包含更多信息的DTO列表
            List<Map<String, Object>> commandData = new ArrayList<>();
            for (RobotArmCommand cmd : commands) {
                Map<String, Object> cmdMap = new HashMap<>();
                cmdMap.put("robotArmCommandId", cmd.getRobotArmCommandId());
                cmdMap.put("trayCode", cmd.getTrayCode());
                cmdMap.put("storeyCode", cmd.getStoreyCode());
                cmdMap.put("status", cmd.getStatus());
                commandData.add(cmdMap);
            }

            Map<String, Object> message = new HashMap<>();
            message.put("type", type);
            message.put("data", commandData);
            return mapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            return "{\"error\":\"Failed to serialize data\"}";
        }
    }

    public void broadcastCommandUpdate() {
        List<RobotArmCommand> loadingCommands = robotArmCommandService.findByType("0");
        List<RobotArmCommand> unloadingCommands = robotArmCommandService.findByType("1");

        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(createMessage("loading", loadingCommands)));
                    session.sendMessage(new TextMessage(createMessage("unloading", unloadingCommands)));
                } catch (IOException e) {
                    // 处理异常
                }
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
    }

    /**
     * 广播状态消息给所有客户端
     */
    public void broadcastStatus(String status) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", "status");
            message.put("data", status);
            String jsonMessage = mapper.writeValueAsString(message);

            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    try {
                        session.sendMessage(new TextMessage(jsonMessage));
                    } catch (IOException e) {
                        log.error("发送状态消息到WebSocket失败", e);
                    }
                }
            }
        } catch (JsonProcessingException e) {
            log.error("序列化状态消息失败", e);
        }
    }
}
