<template>
    <div>
      <!-- <button @click="open()">断开</button>
      <button @click="con()">重连</button> -->
    </div>
</template>
<script lang="ts" setup>
import { useStore } from '/@/store/index';
import { ref,getCurrentInstance,defineEmits,onMounted, computed,onBeforeMount, h, onBeforeUnmount } from 'vue';
import { ElNotification } from 'element-plus'
const wss=import.meta.env.VITE_API_WSS as any
const emit = defineEmits([ "retBody" ]);
//引入使用SockJS
// import { store } from '/@/store/index.ts';
import Stomp from "stompjs";
import {formatDate,jgTime3} from "/@/utils/formatTime.ts";
let subscribePush=[]
const store = useStore();
const clientCode = computed(() => {
  return store.state.userInfos.userInfos.client.code;
});
const userCode = computed(() => {
  return store.state.userInfos.userInfos.userCode;
});
//stomp客户端
let stompClient: Stomp.Client;
//连接状态
let connetStatus = false;
/**
 * 初始化连接
 */
 const initSocket = () => {
  con();
  setInterval(() => {
    console.log('10miao chonglian')
    //根据连接状态
    if (connetStatus===false) {
      try {
        console.log('websockte断开准备重连')
        con();
      } catch (error) {
        console.log(error)
      }
    }
  }, 10000);
};
/**
 * 连接
 */
const con = () => {
  if(connetStatus){
    return 
  }
  console.log(wss)
  // let socket =  new WebSocket('wss://hemobs.icoldchain.cn/broadcast')
    let socket =  new WebSocket(wss)
  

  stompClient = Stomp.over(socket);

  let header = {};
  stompClient.connect(
    header,
    (res) => {
      console.log('------kankan返回')
      console.log(res)
      console.log("===========connect success===========");
      connetStatus = true;
      // if(subscribePush.findIndex(e=>{return e=='/queue/test/message/request'})==-1){
      // stompClient.subscribe(
      //     // `/queue/push/msg/${clientCode.value}/request`,
      //     '/queue/test/message/request',
      //     (res: any) => {
      //       subscribePush.push(`/queue/push/msg/${clientCode.value}/request`)
      //         console.log('订阅后返回客户消息',formatDate(new Date(),'YYYY-mm-dd HH:MM:SS'))
      //         var dataBody = JSON.parse(res.body)
      //         console.log(dataBody)
      //       if(dataBody!==undefined){
      //         ElNotification({
      //           title: '99',
      //           // dangerouslyUseHTMLString: true,
      //           message: dataBody.msg,
      //           duration: 4500,
      //         })
      //       }
      //     },
      //     header
      //   );
      // }
      //设置订阅
      //1: /queue/push/msg/{clientCode}/request  这是客户下的所有用户都会收到的推送
      if(subscribePush.findIndex(e=>{return e==`/queue/push/msg/${clientCode.value}/request`})===-1){
        subscribePush.push(`/queue/push/msg/${clientCode.value}/request`)
        stompClient.subscribe(
          `/queue/push/msg/${clientCode.value}/request`,
          // '/queue/test/message/request',
          (res: any) => {
            subscribePush.push(`/queue/push/msg/${clientCode.value}/request`)
              console.log('订阅后返回客户消息',formatDate(new Date(),'YYYY-mm-dd HH:MM:SS'))
              var dataBody = JSON.parse(res.body)
              console.log(dataBody)
            if(dataBody!==undefined){
              ElNotification({
                title: dataBody.taskSender,
                dangerouslyUseHTMLString: true,
                message: dataBody.taskPara,
                duration: 10000,
              })
            }
          },
          header
        );
      }
      if(subscribePush.findIndex(e=>{return e==`/queue/push/msg/${clientCode.value}/${userCode.value}/request`})===-1){
        //2: /queue/push/msg/{clientCode}/{userCode}/request  这是客户下的某个用户才会收到的推送
        subscribePush.push(`/queue/push/msg/${clientCode.value}/${userCode.value}/request`)
        stompClient.subscribe(
          `/queue/push/msg/${clientCode.value}/${userCode.value}/request`,
          (res: any) => {
              console.log('订阅后返回用户消息',formatDate(new Date(),'YYYY-mm-dd HH:MM:SS'))
              var dataBody = JSON.parse(res.body)
              console.log(dataBody)
            if(dataBody!==undefined){
              const data=new Date()
              ElNotification({
                title: dataBody.taskSender,
                dangerouslyUseHTMLString: true,
                message: dataBody.taskPara,
                duration: 10000,
                onClose:()=>{
                  console.log(dataBody.code,'0000')
                  // 看看是否是自己关闭的
                  const jg= jgTime3(data)
                  // 自动关闭的 
                  if(jg>=10){
                    console.log('10秒自动关闭')
                  }else{
                    console.log('手动关闭')
                  }
                }
                
              })
            }
          },
          header
        );
      }
    },
    (err: any) => {
      console.log("error");
      console.log(err);
      // 出现异常就断开重连
      close()
    }
  );
};
const open=()=>{
  const data=new Date()
 ElNotification({
    title: 'nihao',
    dangerouslyUseHTMLString: true,
    message: '<div>dasdasd2222</div>',
    duration: 3000,
    onClose:()=>{
      console.log(jgTime3(data))
    }
    
  })
    
}
const close_notify=()=>{
  alert('sss')
}
/**
 * 断开
 */
const close = () => {
  console.log('注销socket-----')
  if (stompClient) {
    console.log('注销socket2222-----')
    stompClient.disconnect(() => {
      console.log("============connect release============");
      connetStatus = false;
      subscribePush=[]
    });
  }
};
onMounted(()=>{
    // 打开socket
    initSocket()
    
}),
// 取消订阅
onBeforeMount(()=>{
  alert(1)
  close()
})
// onBeforeUnmount(()=>{
//   alert(2)
//   close()
// })


</script>
