<template>
    <div></div>
</template>
<script lang="ts" setup>
import { ref,defineExpose,defineEmits,onMounted } from 'vue';
import { useRoute } from 'vue-router';
const emit = defineEmits([ "retBody" ]);
//引入使用SockJS
import Stomp from "stompjs";
import {formatDate} from "/@/utils/formatTime.ts";
const wss=import.meta.env.VITE_API_WSS as any
const router = useRoute();
const clientCode=ref('')
//stomp客户端
let stompClient: Stomp.Client;
//连接状态
let connetStatus = false;
/**
 * 初始化连接
 */
 const initSocket = () => {
  con();
  setInterval(() => {
    console.log('当前是连接状态：'+connetStatus)
    //根据连接状态
    if (connetStatus) {
      try { 
        
      } catch (error) {
       
      }
    }else{
      console.log('websockte异常断开准备重连')
      console.log('开始重连----')
      con();
    }
  }, 10000);
};
/**
 * 连接
 */
const con = () => {
    let socket =  new WebSocket(wss)
  stompClient = Stomp.over(socket);

  let header = {};
  stompClient.connect(
    header,
    () => {
      console.log("===========connect 3333success===========");
      connetStatus = true;
      //设置订阅
      stompClient.subscribe(
        `/queue/recv/client/${clientCode.value}`,
        (res: any) => {
            console.log('订阅后返回消息',formatDate(new Date(),'YYYY-mm-dd HH:MM:SS'))
            var dataBody = JSON.parse(res.body)
            emit('retBody',dataBody);
        },
        header
      );
    },
    (err: any) => {
      connetStatus = false;
      console.log("error");
      console.log(err);
    }
  );
};
/**
 * 断开
 */
const close = () => {
  if (stompClient) {
    stompClient.disconnect(() => {
      console.log("============connect release============");
      connetStatus = false;
    });
  }
};
onMounted(()=>{
    console.log(router.query);
	const query = router.query
	if (query === undefined) {
	}
	if (query.pagesize === undefined || query.clientCode === undefined) {
	}
	if (query.clientCode !== '' && query.pagesize !== '') {
        clientCode.value=query.clientCode
        // 打开socket
        initSocket()
	}
    
})


</script>
