import io from "socket.io-client";
import { message } from "antd";

let connectflag = true;

let callNumberSocket = {
  init(serverIP, serverPort) {
    console.log("serverIP, serverPort", serverIP, serverPort)
    if ((window.socket) && (window.socket.connected)) {
      return;
    }
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    //初始化服务器信息
    window.socket = io(serverIP + ":" + serverPort, {
      reconnectionAttempts: 0,
      reconnection: false,
      transports: ["websocket"],
      forceNew: true,
      query: {
        type: 'B',
        deviceID: userData.sessionID + "&" + userData.userID
      }
    });

    //服务器连接超时
    window.socket.on("connect_timeout", function () {
    });

    //服务器连接异常
    window.socket.on("connect_error", function () {
      window.socket.close();
    });

    window.socket.on("disconnect", function () {
      window.socket.close();
    });

    window.socket.on("reconnecting", function () {
      window.socket.close();
    });

    //服务器连接或重连成功
    window.socket.on("connect", function (data) {
      if (!connectflag) {
        //message.warn("叫号服务器已重连成功,请重新呼叫!");
      }
      connectflag = true;
    });

    //服务器响应消息
    window.socket.on("respond", function (data) {
      if (data == "0") {
        message.success("叫号成功");
      } else {
        message.warn(data);
      }
    });
  },

  //发送消息
  sendMsg(msg) {
    console.log('msg', msg)
    if (window.socket.connected) {
      console.log("window.socket.connected", window.socket.emit)
      window.socket.emit("callNumber", JSON.stringify(msg));
    } else {
      if (window.socket) {
        console.log("window.socket")
        connectflag = false;
        window.socket.open();
        setTimeout(() => {
          window.socket.emit("callNumber", JSON.stringify(msg));
        }, 2000)
        //message.warn("服务器连接失败,尝试重连中!");
      }
    }
  },

  //关闭链接
  colse() {
    if (window.socket) window.socket.close();
  },

  //打开链接
  open() {
    if (window.socket) window.socket.open();
  }
};

export { callNumberSocket };
