import Stomp from "stompjs";
import store from '@store/index';
var projectconfig = `ws://${window.__MODE__.websocketUrl}`;
// ============================一般使用的变量============================
let number = 0;
export const datainit = initialize;
export const webtest = test;

// ============================  大函数体   ============================
function initialize (topic, adpClient) {

  if (adpClient != null) {
    adpClient.disconnect();
  }

  var url = projectconfig;
  // let socket = new SockJS(url);  // 这个地址要找你们后端
  // adpClient = Stomp.over(socket);
  adpClient = Stomp.client(url);
  adpClient.debug = null;

  adpClient.connect({ topic: topic, authToken: localStorage.getItem('authToken') }, adpClient2 => connectCallBackSubscribe(adpClient, topic), error => reconnect(error, adpClient, topic));

  return adpClient;
}
// 断线重连
function reconnect (error, adpClient, topic) {
  //连接失败时再次调用函数
  number++;
  adpClient.connected = false;
  clearTimeout(setTimeout(initialize(topic), 1000 * 60 * 5));
  debugX("DataAdapter reconnect:" + number + " 次");
  return;
}
// ============================  订阅函数体  ============================
function connectCallBackSubscribe (adpClient, topic) {
  number = 0;
  adpClient.connected = true;
  adpClient.subscribe(topic, stompMessage => reflexWindturbineBasicInformation(stompMessage));
}
// ============================  解析函数体  ============================
function reflexWindturbineBasicInformation (stompMessage) {
  var newdata = JSON.parse(stompMessage.body);
  store.dispatch('getupdate', newdata);
  // console.log("newdata", newdata);

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

function test () {
  clearTimeout(setTimeout(initialize('/topic/detial/param_MG01_02'), 1000 * 60 * 2));
}

