import { ref, onBeforeUnmount } from "vue";
import { Client } from "@stomp/stompjs";
import { showToast } from "vant";
import store from "@/store/index";
import { userLogin } from "@/utils/login";
import lifecycle from "page-lifecycle";
import dayjs from "dayjs";
import emitter from "@/utils/emitter";
import { getSystem } from "@/utils/index";

export default function ({ id, privateMessage, chatMessage }) {
  onBeforeUnmount(() => {
    stompClient.value && stompClient.value.deactivate();
  });
  const stompClient = ref();
  let playCtxObj = null; // 播放器对象
  let closeNum = 0; // WebSocket关闭次数
  let connectNum = 0; // 程序去主动连接次数
  let connectTime = null;
  let sessionId = "";
  const system = getSystem();
  const connect = async () => {
    console.log("connect建立连接");
    const frontToken = store.state.token;
    if (
      localStorage.getItem(`sessionId-${store.state.userInfo.userId}-${id}`)
    ) {
      sessionId = localStorage.getItem(
        `sessionId-${store.state.userInfo.userId}-${id}`
      );
    } else {
      sessionId = Math.random().toString(36).substring(2, 8);
      localStorage.setItem(
        `sessionId-${store.state.userInfo.userId}-${id}`,
        sessionId
      );
    }
    console.log("frontToken", frontToken);

    const brokerUrl = `${location.protocol === "http:" ? "ws://" : "wss://"}${
      location.host
    }/tgim/chat`;
    stompClient.value = new Client({
      brokerURL: `${
        process.env.NODE_ENV === "development"
          ? "ws://8.138.144.54:8080/tgim/chat"
          : brokerUrl
      }`,
      connectHeaders: {
        sessionId,
        token: store.state.token,
        productType: 41, //  3 直播 41交易圈
        productId: id,
      },
      debug: function (str) {
        console.log("debug: " + dayjs().format("YYYY-MM-DD HH:mm:ss") + str);
      },
      reconnectDelay: 5000,
      heartbeatIncoming: 10000,
      heartbeatOutgoing: 10000,
      discardWebsocketOnCommFailure: true,
    });
    stompClient.value.onConnect = async (frame) => {
      // setConnected(true);
      console.log("链接成功");
      console.log("Connected: ", frame);
      closeNum = 0;
      connectNum = 0;
      clearTimeout(connectTime);
      emitter.emit("cancelGetNewMsg");
      // 接收群聊接收消息路径
      chatMessage &&
        (await stompClient.value.subscribe(
          `/app/group/topic/${id}`,
          chatMessage
        ));
      // APP端私聊消息
      privateMessage &&
        (await stompClient.value.subscribe(
          `/app/private/topic/${id}/${store.state.userInfo.userId}`,
          privateMessage
        ));
    };
    stompClient.value.onStompError = (error) => {
      console.log(error.body);
      if (
        error.body.includes("2007") ||
        error.body.includes("2000") ||
        error.body.includes("2003")
      ) {
        userLogin();
      } else {
        showToast(`${error.body}`);
      }
    };
    stompClient.value.onDisconnect = (error) => {
      console.log("onDisconnect", error);
      stompClient.value = null;
    };

    const anewConnectFn = () => {
      clearTimeout(connectTime);
      connectTime = setTimeout(() => {
        if (connectNum < 5) connectNum++;
        connect();
        anewConnectFn();
      }, connectNum * 60 * 1000);
    };

    stompClient.value.onWebSocketClose = (error) => {
      console.log("onWebSocketClose", closeNum, error);
      if (closeNum > 3) {
        closeNum = 0;
        stompClient.value && stompClient.value.deactivate();
        emitter.emit("getNewMsg");
        anewConnectFn();
      } else {
        closeNum++;
      }
    };
    stompClient.value.activate();
  };

  connect();

  window.addEventListener("unload", function (event) {
    stompClient.value && stompClient.value.deactivate();
    console.log("stompClient.value", stompClient.value);
    event.returnValue = "你确定要离开这个页面吗？";
  });
  lifecycle.addEventListener("statechange", function (event) {
    console.log("statechange", event.newState, playCtxObj);
    if (system === "ios") {
      if (event.newState === "hidden" && playCtxObj) {
        playCtxObj.pause();
      } else if (playCtxObj) {
        playCtxObj.play();
      }
    }
  });
  return {
    stompClient,
  };
}
