package com.dayou.websocket;

import com.alibaba.fastjson.JSON;
import com.dayou.utils.LoginContext;
import com.dayou.vo.TaskReminderVO;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import static com.dayou.common.Constants.USER_ID;

/**
 * 类说明：
 *
 * @author: wucl
 * @since: 2023/7/20
 * created with IntelliJ IDEA.
 */
@Component
@ServerEndpoint(value="/ws",configurator = WebSocketConfig.class)
public class WebSocketServer {

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    private String key;

    private Session session;

    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        Object attribute = httpSession.getAttribute(USER_ID);
        if (attribute != null) {
            key = String.valueOf(attribute);
            this.session = session;
            System.out.println("当前登录用户id:" + key);
            atomicInteger.incrementAndGet();
            System.out.println("建立连接成功 onOpen 线程数量："+atomicInteger.get()+" sessionID："+ key);
            System.out.println("当前socket连接数量:" + webSocketMap.size());
            webSocketMap.put(key,this);
        }

    }

    /**
     * 连接关闭调用的方法
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        System.out.println("一个客户端断开连接:" + key);
        atomicInteger.incrementAndGet();
        if (key!=null){
            webSocketMap.remove(key);
        }
    }

    /**
     * 接收到客户端消息后调用的方法
     * @param msg 客户端发送的消息
     * @param session
     */
    @OnMessage
    public void onMessage(String msg, Session session) throws IOException {
        atomicInteger.incrementAndGet();
        System.out.println("接收到客户端发送的消息 onMessage："+ msg+" 线程数量："+atomicInteger.get()+" sessionID："+session.getId());
        session.getBasicRemote().sendText(msg);
    }

    /**
     * 出现错误时调用的方法
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable){
        atomicInteger.incrementAndGet();
        System.out.println("错误 onError 线程数量："+atomicInteger.get()+" sessionID："+session.getId());
        throwable.printStackTrace();
    }

    /**
     * 发送节点待办提醒
     * @param taskReminderVO
     */
    public void sendNodeReminder(TaskReminderVO taskReminderVO){
        if (webSocketMap.size()>0){
            for(Map.Entry<String, WebSocketServer> map : webSocketMap.entrySet()){
                try {
                    if (map.getKey().equals(String.valueOf(taskReminderVO.getHandlerId()))){
                        map.getValue().session.getBasicRemote().sendText(JSON.toJSONString(taskReminderVO));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
