package com.junmp.jyzb.websocket;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.junmp.jyzb.api.bean.query.WsWarehouseReq;
import com.junmp.jyzb.cache.DeviceRedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/device/ws")
@Slf4j
public class WarehouseWebSocketServer {

    private final String STORE_WEB_KEY = "store_web";

    @Resource
    private DeviceRedisCache redisCache;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 每个客户端对应的Session
     */
    private static Map<String, WarehouseWebSocketServer> storeWebSessionMap = new ConcurrentHashMap<>();

    private Session storeWebSession;

    @OnOpen
    public void connect(Session session) {
        try {
            this.storeWebSession = session;
            String keyVal = StrUtil.format("{}_{}", STORE_WEB_KEY, session.getId());
            storeWebSessionMap.putIfAbsent(keyVal, this);
        } catch (Exception ex) {
            log.error("[设备接入异常]|异常信息：{}", ex.getMessage());
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        try {
            log.info("[接收客户端请求]|请求参数：{}", message);
            String keyVal = StrUtil.format("{}_{}", STORE_WEB_KEY, session.getId());
            WsWarehouseReq deviceData = JSON.parseObject(message, WsWarehouseReq.class);
            String orgId = deviceData.getOrgId();
            String redisExist = redisCache.get(orgId);
            String jsonData = JSON.toJSONString(deviceData);
            if (redisExist != null) {
                redisCache.put(orgId, jsonData);
            } else {
                redisCache.put(orgId, jsonData);
                redisCache.put(keyVal, orgId);
            }
            //推送消息到对应组织机构
            TopicExchange exchange = new TopicExchange("topicExchange");
            rabbitAdmin.declareExchange(exchange);
            String exchangeName = "topicExchange";
            rabbitTemplate.convertAndSend(exchangeName, orgId, "设备上线");
            WsMsgProduce.sendMessage(session, "true");
        } catch (Exception ex) {
            WsMsgProduce.sendMessage(session, "false");
        }
    }

    @OnClose
    public void onClose() {
        try {
            String keyVal = StrUtil.format("{}_{}", STORE_WEB_KEY, storeWebSession.getId());
            WarehouseWebSocketServer oldSession = storeWebSessionMap.get(keyVal);
            if (null != oldSession) {
                String orgId = redisCache.get(keyVal);
                redisCache.remove(keyVal);
                redisCache.remove(orgId);

                //将消息推到对应组织机构
                TopicExchange exchange = new TopicExchange("DevMonitorMsg");
                String exchangeName = "DevMonitorMsg";
                rabbitAdmin.declareExchange(exchange);
                rabbitTemplate.convertAndSend(exchangeName, orgId, "设备下线");
            }
        } catch (Exception ex) {
            log.error("[Ws断开异常]|异常信息：{}", ex.getMessage());
        }
    }
}
