import { defineStore } from 'pinia';
import { ref } from 'vue';
import { sendSock, createWebSocket, closeSock } from '@/utils/websocket.js';
export const websocketStore = defineStore('websocket', () => {
  /**
   * socket推送过来的全量数据，暴露出去用户对数据变更的监听
   */
  const serviceMsg = ref({});

  /**
   * websocket的回调函数
   * @param jsonMsg 表示收到的消息
   */
  const global_callback = (jsonMsg) => {
    serviceMsg.value = jsonMsg;
  };

  /**
   * 连接webSocket init
   */
  const init = ({ experiment_type, isActiveClose }) => {
    createWebSocket(global_callback, experiment_type, isActiveClose);
  };
  /**
   * webSocket发送消息
   * @param sendData 发送的json数据
   */
  const send = (sendData) => {
    sendSock(JSON.stringify(sendData));
  };

  /**
   * 关闭webSocket
   */
  const close = ({ isActiveClose = false }) => {
    closeSock({ activeClose: isActiveClose });
  };

  /**
   * 关闭后重启socket
   */
  const closeAndRestart = () => {
    close({ isActiveClose: true });
    init();
  };

  return {
    init,
    close,
    closeAndRestart,
    serviceMsg,
    send
  };
});
