package com.inspur.websoket.client;

import com.alibaba.fastjson2.JSONObject;
import com.inspur.common.utils.spring.SpringUtils;
import com.inspur.thrid.IPBXService;
import com.inspur.thrid.PBXConstant;
import com.inspur.thrid.impl.PBXServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

@Slf4j
public class PBXWebSocketClient extends WebSocketClient {

    public PBXWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    private IPBXService pbxService = SpringUtils.getBean(PBXServiceImpl.class);

    /**
     * 连接服务端时触发
     * @param handshakedata
     */
    @Override
    public void onOpen(ServerHandshake handshakedata) {
        log.info("websocket客户端和服务器连接成功");
        // 发生订阅消息
        log.info("websocket客户端发送订阅消息");
        String subscribeMessage = PBXConstant.SUBSCRIBE_MESSAGE_LIST;
        this.send(subscribeMessage);
    }

    /**
     * 收到服务端消息时触发
     * @param message
     */
    @Override
    public void onMessage(String message) {
        log.info("websocket客户端收到消息 : {}", message);
        // 心跳响应特殊处理
        if (PBXConstant.WS_HEARTBEAT_RSP.equals(message)) {
            log.debug("收到心跳响应");
            return;
        }
        // 处理收到的消息
        JSONObject messageJson = JSONObject.parseObject(message);
        Integer eventType = messageJson.getInteger("type");
        if (PBXConstant.EVENT_DTMF.equals(eventType)) {
            // DTMF 按键信息
            pbxService.dtmfEvent(messageJson);
        }else if (PBXConstant.EVENT_CALL_STATE_CHANGE.equals(eventType)) {
            // 监听呼叫状态变化
            pbxService.callStateChange(messageJson);
        }else if (PBXConstant.EVENT_NEW_CALL_RECORD.equals(eventType)) {
            pbxService.newCallDetails(messageJson);
        }else {
            return;
        }

    }
    /**
     * 和服务端断开连接时触发
     * @param code
     * @param reason
     * @param remote
     */
    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("websocket客户端退出连接");
    }

    /**
     * 连接异常时触发
     * @param ex
     */
    @Override
    public void onError(Exception ex) {
        log.info("websocket客户端和服务器连接发生错误={}", ex.getMessage());
    }

}
