import Stomp from 'stompjs'
import myconfig from '@api/config'
import store from '@store/index'

// ============================一般使用的变量============================
let number = 0;

// ============================  大函数体   ============================
export function init(topic) {
  let wsClient = null;
  var url = myconfig.webSoketUrl;
  // let socket = new SockJS(url);  // 这个地址要找你们后端
  // wsClient = Stomp.over(socket);
  wsClient = Stomp.client(url);
  wsClient.debug = null;
  wsClient.connect({ topic: topic }, wsClient2 => connectCallBackSubscribe(wsClient, topic), error => reconnect(error, wsClient));
}
// 断线重连
export function reconnect(error, wsClient) {
  //连接失败时再次调用函数
  number++;
  wsClient.connected = false;
  clearTimeout(setTimeout(init('/topic/popup'), 1000 * 5));
  debugX("DataAdapter reconnect:" + number + " 次");
  return;
}
// 链接并推送数据
export function connectCallBackSubscribe(wsClient, topic) {
  number = 0;
  wsClient.connected = true;
  wsClient.subscribe(topic, stompMessage => reflexWindturbineBasicInformation(stompMessage));
}
// ============================  解析函数体  ============================
export function reflexWindturbineBasicInformation(stompMessage) {
  var newdata = JSON.parse(stompMessage.body);
  // store.dispatch('getupdate', newdata);
  console.log(newdata)

}
// ============================  其他  ============================
export function debugX(text) {
  console.log(text);
}

export function close(params) {
  // console.log("关闭socket")
  socket.close();
}


export default {
  init,
  close
}
