package com.zcxk.util;

import com.alibaba.fastjson.JSONObject;
import com.zcxk.entity.WebsocketConnectInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketUtil {
    @Value("${receive.exchange.name}")
    private String exchangeName;
    @Value("${receive.routing.key}")
    private String routingKey;
    @Value("${user.connections}")
    private String connectInfo;
    private RedisUtil redisUtil;


    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName){
        sessionPools.put(userName, session);

        if(redisUtil==null){
             redisUtil = SpringContextUtil.getBean(RedisUtil.class);
        }
        if(exchangeName==null){
            Environment env = SpringContextUtil.getBean(Environment.class);
             exchangeName = env.getProperty("receive.exchange.name");
             routingKey = env.getProperty("receive.routing.key");
             connectInfo = env.getProperty("user.connections");

        }
        WebsocketConnectInfo websocketConnectInfo=new WebsocketConnectInfo();
        websocketConnectInfo.setUserId(userName);
        websocketConnectInfo.setConnectServerExchange(exchangeName);
        websocketConnectInfo.setConnectServerRoutingKey(routingKey);
        //保证一个用户只有一个连接信息被记录
        redisUtil.opsForList().remove(connectInfo,0,JSONObject.toJSONString(websocketConnectInfo));
        redisUtil.opsForList().leftPush(connectInfo, JSONObject.toJSONString(websocketConnectInfo));
        System.out.println(userName + "加入webSocket！" );
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName){
        sessionPools.remove(userName);
        WebsocketConnectInfo websocketConnectInfo=new WebsocketConnectInfo();
        websocketConnectInfo.setUserId(userName);
        websocketConnectInfo.setConnectServerExchange(exchangeName);
        websocketConnectInfo.setConnectServerRoutingKey(routingKey);
        RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);
        redisUtil.opsForList().remove(connectInfo,0,JSONObject.toJSONString(websocketConnectInfo));
        System.out.println(userName + "断开webSocket连接" );
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException{
        message = "客户端：" + message + ",已收到";
        //System.out.println(message);
        for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
