package com.steerinfo.ems.websocket.controller;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

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.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Shadow
 * @create 2021-09-18 14:54
 * @project xt-ems-api
 * 此注解相当于设置访问URL
 *
 */
@ServerEndpoint("/websocket/{shopId}")
@RestController
@Component
public class WebSocket implements ChannelAwareMessageListener {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    private Queue createWsDirectQueue;
    @Value("${spring.rabbitmq.wsExchangeName}")
    private String wsDirectExchange;

    //RabbitTemplate rabbitTemplate = ApplicationContext.getBean(RabbitTemplate.class);

    private Session session;

    private static final CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static final Map<String,Session> sessionPool = new HashMap<String,Session>();

    /**
     * 发送到消息队列
     * @param msg
     */
    public void sendMessage(String msg){
        rabbitTemplate.convertAndSend("ems_webSocket",msg);
    }

    //@RabbitListener(queues = "ems_webSocket")
    public void receiveMessage(String msg){
        System.out.println("收到消息："+msg);
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】rabbitMq广播消息:"+msg);
            try {
                // 判断to用户是否在线
                //if (webSocket.session != null && webSocket.session.isOpen()) {
                //    //TODO 具体格式需要和前端对接
                //    //toSession.sendMessage(new TextMessage(msgJson));
                //    // 更新消息状态为已读
                //    //this.messageDAO.updateMessageState(message.getId(), 2);
                   webSocket.session.getAsyncRemote().sendText(msg);
                //}else{
                //    // 该用户可能下线，可能在其他的节点中，发送消息到MQ系统
                //    // 需求：添加tag，便于消费者对消息的筛选
                //    this.rabbitTemplate.convertAndSend("ems_webSocket",message);
                //}
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value="shopId")String shopId) {
        this.session =  session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        System.out.println("【websocket消息】有新的连接，总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void socket_onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
        //this.sendAllMessage(message);
        //WebSocket webSocket = new WebSocket();
        //webSocket.sendAllMessage(message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        System.out.println("【websocket消息】广播消息:"+message);
        String queueName = createWsDirectQueue.getName();
        rabbitTemplate.convertAndSend(wsDirectExchange,"ems",message);
    }

    // 此为单点消息
    public void sendOneMessage(String shopId, String message) {
        Session session = (Session) sessionPool.get(shopId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 如果没有继承ChannelAwareMessageListener可以将该方法指定为适配器的接收方法，
     * 如果继承了ChannelAwareMessageListener，则优先执行onMessage方法；
     * @param msg
     */
    public void handleMessage1(String msg) {
        System.out.println("handleMessage默认方法，消息内容 String：" + msg);
    }

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】rabbitMq广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(new String(message.getBody()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}