import { env } from "./env";
import { useAuthStore } from "./store";

/**
 * 最大链接次数
 */
const maxConnNum = 5;
/**
 * 链接次数
 */
let connNum = 0;

/**
 * 重连间隔
 */
const connTimeout = 5000;
let timer = undefined;


let ws = undefined;
const connect = () => {
  if (!useAuthStore().isLogin) {
    reconnect();
    return;
  }
  if (ws != undefined) {
    return;
  }
  ws = uni.connectSocket({
    url: env.baseWs.replace('{host}',location.host) + '?Authorization=Bearer ' + useAuthStore().token,
    multiple: false,
    success: () => {
      connNum = 0;
      uni.onSocketClose(() => {
        console.debug("websocket关闭")
        // reconnect();
      });
      uni.onSocketOpen(() => {
        console.debug("websocket已打开")
      })
      uni.onSocketError(() => {
        console.debug("websocket错误重连")
        reconnect();
      })
      uni.onSocketMessage(e => {
        let data = {};
        try {
          data = JSON.parse(e.data);
        } catch (e) {
          data = e.data;
        }
        if (data?.action) {
          uni.$emit(data.action, data);
        } else {
          uni.$emit("text ", data);
        }
      })
    }, fail: () => {
      connNum++;
      if (connNum < maxConnNum) {
        console.error("websocket重连次数已经用完");
      } else {
        reconnect();
      }
    }
  });
}

const send = (action, data) => {
  ws.send({ data: JSON.stringify({ action, data }) });
}


const reconnect = () => {
  try {
    if (ws != undefined) {
      uni.closeSocket(ws)
      ws = undefined
    }
  } catch (e) {
  }
  console.debug("websocket重连");
  if (timer == undefined) {
    timer = setTimeout(() => {
      timer = undefined;
      connect();
    }, connTimeout);
  }
}

const resetconnect = () => {
  connNum = 0;
  reconnect();
}

const close = () => {
  try {
    uni.closeSocket(ws)
    ws = undefined
    connNum = 0;
  } catch (e) {
  }
}

const useWebSocket = {
  install(Vue) {
    // connect();
  }
}

setInterval(() => {
  try {
    ws.send({ data: "ping" });
  } catch (e) {

  }
}, 30000);

export {
  connect, reconnect, resetconnect, close, send, useWebSocket
}