package com.fjhx.victoriatourist.service.jd.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.fjhx.socket.core.WebSocketServer;
import com.fjhx.socket.core.event.WebSocketOnMessageEvent;
import com.fjhx.socket.core.event.WebSocketOnOpenEvent;
import com.fjhx.victoriatourist.entity.jd.vo.JdInfoVo;
import com.fjhx.victoriatourist.service.jd.JdInfoService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;

@Component
public class JdWebSocket {
    @Resource
    JdInfoService jdInfoService;

    @EventListener
    public void webSocketOnOpenEvent(WebSocketOnOpenEvent webSocketonOpenEvent) {
        WebSocketServer websocketserver = webSocketonOpenEvent.getWebSocketServer();
    }

    @EventListener
    public void webSocketOnMessageEvent(WebSocketOnMessageEvent webSocketOnMessageEvent){
        String message = webSocketOnMessageEvent.getMessage();
        JSONObject msgObj;
        try {
            msgObj = JSONObject.parseObject(message);
            String cmd = msgObj.getString("cmd");
            if ("jdStatus".equals(cmd)) {
                WebSocketServer websocketserver = webSocketOnMessageEvent.getWebSocketServer();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cmd", "jdStatus");
                Random random = new Random();
                //从数据库中获取并返回
                JdInfoVo jdInfoVo = jdInfoService.getOne();
                int status = jdInfoVo.getOnline();
                jsonObject.put("status", status>0?true:false);
                websocketserver.getSession().getBasicRemote().sendText(jsonObject.toJSONString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
