import io from "socket.io-client";
import { message } from "antd";
import { $http } from "../containers/config/https";
let MessageSocket = {
  init(callback) {
    let userData = sessionStorage.userData
      ? JSON.parse(sessionStorage.userData)
      : {};
    let data = {
      params: [
        {
          code: "Msg"
        }
      ]
    };
    $http.post("urlS", this, {
      code: "04180001",
      data: data,
      success: function(res) {
        if (+res.errorCode === 0 && res.result != undefined) {
          //初始化服务器信息
          window.sessionStorage.setItem(
            "messageServer",
            JSON.stringify(res.result)
          );
          window.messageSocket = io(res.result.IP + ":" + res.result.port, {
            transports: ["websocket"],
            forceNew: true,
            query: {
              userID: userData.userID,
              sessionID: userData.sessionID
            }
          });
          //服务器连接超时
          window.messageSocket.on("connect_timeout", function() {
             
          });
          //服务器连接异常
          window.messageSocket.on("connect_error", function() {
            if (window.messageSocket) window.messageSocket.close();
          });
          window.messageSocket.on("disconnect", function() {
             
          });
          window.messageSocket.on("reconnecting", function() {
            
          });
          //服务器连接或重连成功
          window.messageSocket.on("connect", function(data) {
             
          });
          //服务器响应消息
          window.messageSocket.on("respondMessage", function(data) {
            if (callback) {
              callback(data);
            }
          });
        }else{
          if (window.messageSocket) window.messageSocket.close();
        }
      }
    });
  },
  //关闭链接
  colse() {
    if (window.messageSocket) window.messageSocket.close();
  },
  //打开链接
  open() {
    if (window.messageSocket) window.messageSocket.open(); 
  }
};
export { MessageSocket };
