package com.ecep.contract.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

import org.springframework.web.socket.PingMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.ecep.contract.constant.WebSocketConstant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;

@Data
public class SessionInfo {
    private Integer employeeId;
    private Integer loginHistoryId;
    private WebSocketSession session;
    private ObjectMapper objectMapper;
    private ScheduledFuture<?> pingPongScheduledFuture;

    public void click() {
        try {
            session.sendMessage(new PingMessage(ByteBuffer.wrap("ping".getBytes())));
        } catch (IOException e) {
            WebSocketServerHandler.logger.error("发送ping消息失败 (会话ID: " + session.getId() + "): " + e.getMessage(), e);
        }
    }

    public void sendError(int errorCode, String errorMessage) throws JsonProcessingException, IOException {
        Map<String, Object> data = Map.of(
                WebSocketConstant.ERROR_CODE_FIELD_NAME, errorCode,
                WebSocketConstant.SUCCESS_FIELD_NAME, false,
                WebSocketConstant.MESSAGE_FIELD_NAME, errorMessage);
        send(objectMapper.writeValueAsString(data));
    }

    public void sendError(String extendField, String extendValue, int errorCode, String errorMessage)
            throws JsonProcessingException, IOException {
        Map<String, Object> data = Map.of(
                extendField, extendValue,
                WebSocketConstant.ERROR_CODE_FIELD_NAME, errorCode,
                WebSocketConstant.SUCCESS_FIELD_NAME, false,
                WebSocketConstant.MESSAGE_FIELD_NAME, errorMessage);
        send(data);
    }

    public void send(Map<String, Object> data) throws JsonProcessingException, IOException {
        send(objectMapper.writeValueAsString(data));
    }

    public void send(String text) throws IOException {
        if (session == null || !session.isOpen()) {
            throw new IOException("会话已关闭，无法发送消息");
        }
        session.sendMessage(new TextMessage(text));
    }
}