package com.cico.nest.lcdp.boot.core.qxsd.adapter.ws;

import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.TunnelHoleMapper;
import com.cico.nest.lcdp.boot.core.qxsd.infrastructure.gatewayimpl.database.dataobject.TunnelHoleV2DO;
import jakarta.annotation.Resource;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 测试带参数
 * @author zws
 * @date 2024/8/14
 */

@Component
@ServerEndpoint(value = "/qxsd/test")
public class TestWs extends AbstractRealTimeEventWs {

    @Resource
    private TunnelHoleMapper tunnelHoleMapper;
    private String tunnelUpId;
    Logger logger = LoggerFactory.getLogger(RealTimeVehicleWs.class);

    private final static List<Session> sessionList = new CopyOnWriteArrayList<>();


    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        session.setMaxIdleTimeout(60000);
        Object token= session.getRequestParameterMap().get("token");
        System.out.println("建立连接，入参1="+token);
        List<String> param= session.getRequestParameterMap().get("param");
        System.out.println("建立连接，入参2="+param.get(0));
//        List<TunnelHoleV2DO> holes= tunnelHoleMapper.selectList();
        tunnelUpId = "111";
        sessionList.add(session);
        sendMessage("session建立成功！"+param.get(0));
    }

    @OnMessage
    public void onMessage(String message,Session  session){
        System.out.println("来自客户端实时消息："+message);
        System.out.println("来自客户端session："+session.toString());
        sendMessage("服务端收到客户端的消息，并返回客户端发来的消息:"+message);
    }
    /**
     * 发生错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误"+error.getMessage());
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(Session session) {
        sessionList.remove(session);
    }

    @Override
    public String tunnelId() {
        return this.tunnelUpId;
    }

    /**
     * 推送消息
     * @param message
     */
    @Override
    public void sendMessage(String message) {
        for (Session session : sessionList) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                logger.info("服务端发送消息失败"+e.getMessage());
            }
        }
    }

}
