package com.zfire.mall.manager.component;

import cn.hutool.json.JSONUtil;
import com.zfire.mall.manager.bean.socket.ReceiveAndReturnDataBean;
import com.zfire.mall.manager.logic.socket.NoticeDataProcessor;
import com.zfire.mall.manager.utils.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/supply/websocket/{userId}")
public class WebSocket {

    private Session session;

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 缓存 webSocket连接到单机服务class中（整体方案支持集群）
     */
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    /**
     * 线程安全Map
     */
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            //TODO 通过header中获取token，进行check
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            log.info("【websocket消息】连接断开，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            log.debug("来自客户端的消息：{}", message);
            //添加接收到客户端数据后的处理
            ReceiveAndReturnDataBean data = JSONUtil.toBean(message, ReceiveAndReturnDataBean.class, true);
            if (Objects.nonNull(data)) {
                String type = data.getType();
                Object bean = ApplicationContextUtils.getBean(type);
                if (Objects.nonNull(bean)) {
                    NoticeDataProcessor noticeDataProcessor = (NoticeDataProcessor)bean;
                    pushMessage(this.userId, JSONUtil.toJsonStr(noticeDataProcessor.processor(this.userId, data)));
                }
            }
        } catch (Exception e) {
            log.error("接收用户消息出错了:", e);
        }
    }

    /**
     * 服务器端推送消息
     */
    public void pushMessage(String message) {
        try {
            webSockets.forEach(ws -> ws.session.getAsyncRemote().sendText(message));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 服务端推送消息
     *
     * @param userId
     * @param message
     */
    public void pushMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session){
                    log.debug("【websocket消息】 单点消息:" + message);
                    session.getBasicRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
