import { Client } from "@stomp/stompjs";
import { rLiveWsConfig } from "@/api/videoLive";
export default {
  data() {
    return {
      stompClient: null
    };
  },
  beforeDestroy() {
    this.stompClient && this.stompClient.deactivate();
  },
  methods: {
    async getConnectConfig(id) {
      const res = await rLiveWsConfig({ id, type: 9 });
      if (!this.stompClient && res && res.code === 0 && res.data) {
        this.connect({ ...res.data, id });
      }
    },
    // websock 链接
    connect(id) {
      let brokerUrl =
        process.env.NODE_ENV === "development"
          ? "ws://8.138.144.54:8080/tgim/chat"
          : `${location.protocol === "http:" ? "ws://" : "wss://"}${
              location.host
            }/tgim/chat`;
      // 后端群组消息
      const groupChatTopic = `/admin/group/topic/${id}`;
      // 私聊消息
      const privateChatTopic = `/admin/private/topic/${id}`;

      const sessionId = Math.random()
        .toString(36)
        .substring(2, 8);
      if (window.location.protocol === "http:") {
        console.log("当前URL是HTTP");
      } else if (window.location.protocol === "https:") {
        console.log("当前URL是HTTPS");
        brokerUrl = brokerUrl.replace("ws://", "wss://");
      }
      this.stompClient = new Client({
        brokerURL: brokerUrl,
        connectHeaders: {
          sessionId,
          productType: 41, // 视频ProductType=3
          Authorization: "Bearer " + this.$store.state.user.token,
          productId: id
        },
        debug: function(str) {
          console.log("debug: " + str);
        },
        reconnectDelay: 5000,
        heartbeatIncoming: 10000,
        heartbeatOutgoing: 10000,
        discardWebsocketOnCommFailure: true
      });
      this.stompClient.onConnect = async frame => {
        console.log("链接成功");
        console.log("Connected: ", frame);
        // 后端群组消息
        this.stompClient &&
          this.stompClient.subscribe(groupChatTopic, msg => {
            this.handleGroupChatTopic(msg);
          });
        // 后端私聊消息
        this.stompClient &&
          this.stompClient.subscribe(privateChatTopic, msg => {
            this.handlePrivateChatTopic(msg);
          });
      };
      this.stompClient.onStompError = error => {
        console.log("onStompError", error);
      };
      this.stompClient.onDisconnect = error => {
        console.log("onDisconnect", error);
      };
      this.stompClient.onWebSocketClose = error => {
        console.log("onWebSocketClose", error);
      };
      this.stompClient.activate();
    }
  }
};
