//引入使用SockJS
import { store } from '/@/store/index.ts';
import Stomp from "stompjs";
import {formatDate} from "/@/utils/formatTime.ts"
//请求地址
const baseUrl = "http://hemobs.icoldchain.cn/broadcast";
//请求头
const header = {};
//stomp客户端
let stompClient: Stomp.Client;
//连接状态
let connetStatus = false;
/**
 * 初始化连接
 */
export const initSocket = () => {
  con();
  setInterval(() => {
    //根据连接状态
    if (connetStatus) {
      try {
      } catch (error) {
        console.log('websockte断开准备重连')
        con();
      }
    }
  }, 10000);
};
/**
 * 连接
 */
export const con = () => {
  let socket =  new WebSocket('wss://hemobs.icoldchain.cn/broadcast')

  stompClient = Stomp.over(socket);

  let header = {};
  stompClient.connect(
    header,
    () => {
      console.log("===========connect success===========");
      const userClick=store.state.userInfos.userInfos.client.code
      connetStatus = true;
      //设置订阅
      stompClient.subscribe(
        `/queue/recv/client/${userClick}`,
        (res: any) => {
            console.log('订阅后返回消息',formatDate(new Date(),'YYYY-mm-dd HH:MM:SS'))
            var dataBody = JSON.parse(res.body)
            console.log(dataBody);
        },
        header
      );
    },
    (err: any) => {
      console.log("error");
      console.log(err);
    }
  );
};

/**
 * 断开
 */
export const close = () => {
  if (stompClient) {
    stompClient.disconnect(() => {
      console.log("============connect release============");
      connetStatus = false;
    });
  }
};

