<template>
    <div>
     
      <!-- <el-button @click="closeSource">断开</el-button>
      <el-button @click="reconnectSSE">重连</el-button> -->
    </div>
  </template>
  
  <script lang="ts" setup>
    import { getCurrentInstance, onBeforeMount, onMounted, onUnmounted, reactive, ref } from "vue";
    import { useRouter } from 'vue-router'
    import { useStore } from '/@/store/index';
    import { computed } from 'vue';
    import {EventSourcePolyfill} from 'event-source-polyfill';
    import { Session } from "/@/utils/storage";
    import { ElMessageBox, ElNotification, ElMessage } from "element-plus";
    import { jgTime3 } from "/@/utils/formatTime";
    const { proxy } = getCurrentInstance() as any;
    const wss=import.meta.env.VITE_API_URL as any;
    const store = useStore();
    const userCode = computed(() => {
        return store.state.userInfos.userInfos.userCode;
    });
    const router = useRouter()
    // 连接服务器
    
    const source = ref<EventSourcePolyfill | null>(null);
        //接收到的sse数据
    const sseData = ref({});
    // sse状态
    const readyState = ref({ key: 0, value: "正在链接中" });
    const token = Session.get('token');
    //创建链接对象
    const creatSource = () => {
        const stateArr = [
        { key: 0, value: "正在链接中" },
        { key: 1, value: "已经链接并且可以通讯" },
        { key: 2, value: "连接已关闭或者没有链接成功" },
        ];
        try {
        source.value=  new EventSourcePolyfill(`${wss}sse/sseEvent/${userCode.value}`,{
            headers: {
                Token:`Bearer ${token}`, 
            },
            heartbeatTimeout:60000
        });
        // source.value=  new EventSource('http://localhost:3000');
        source.value.onopen = (e) => {
            console.log('链接成功')
            readyState.value = stateArr[source.value?.readyState ?? 0];
            console.log(e)
        };
        source.value.onerror = (e) => {
            console.log(e,'异常情况-----')
            readyState.value = stateArr[source.value?.readyState ?? 0];
        };
        source.value.onmessage = (e) => {
            console.log('收到消息',e.data)
            // store.commit('socketMessage/ADD_WEBSOCKET_MESSAGE', 'CaLoginCompleted');
            if(e.data){
                const msg=e.data
                let dif=msg.indexOf('Dify:')
                let beng=msg.indexOf('{')
                let end=msg.length-1
                // 需要谈到中间的taskType
                const taskTypeByElMessageBoxs = ['AddTempDrugOrder', 'UpdateTempDrugOrder', 'DeleteTempDrugOrder'];
                if(beng!==-1&&end!==-1){
                    const datax=msg.slice(beng,end+1)
                    const dataBody=JSON.parse(datax)
                    console.log('dataBody.taskType: ', dataBody.taskType)
                    // 签到消息
                    if(dataBody.taskType==="PatSign"){
                        const routerda=reactive(router.currentRoute.value)
                        if(routerda.fullPath==='/DialysisRecord/dialysisForm'){
                            console.log(dataBody)
                            const qiandao=JSON.parse(dataBody.taskPara)
                            console.log('得到签到信息')
                            console.log(qiandao)
                            const signDaa={
                                preHemoWeight:qiandao.preHemoWeight,
                                preMBpH:qiandao.preMBpH,
                                preMBpL:qiandao.preMBpL,
                                preMP:qiandao.preMP,
                                recordCode:qiandao.recordCode,
                                updateTime:qiandao.updateTime
                            }
                            console.log(signDaa)
                            // 装载签到信息到vuex
                            store.dispatch('patientInfos/setrecordInfo',signDaa);
                        }else{
                            console.log('有签到  没有改变')
                            return ''
                        }
                        
                       
                    }
                    // 签到消息
                    else if(dataBody.taskType==="PatAfterMedSign"){
                        const routerda=reactive(router.currentRoute.value)
                        if(routerda.fullPath==='/DialysisRecord/dialysisForm'){
                            console.log(dataBody)
                            const qiandao=JSON.parse(dataBody.taskPara)
                            console.log('得到签到信息')
                            console.log(qiandao)
                            const signDaa={
                                afterHemoWeight:qiandao.afterHemoWeight,
                                afterMBpH:qiandao.afterMBpH,
                                afterMBpL:qiandao.afterMBpL,
                                afterMP:qiandao.afterMP,
                                recordCode:qiandao.recordCode,
                                updateTime:qiandao.updateTime
                            }
                            console.log(signDaa,'签到后')
                            // 装载签到信息到vuex
                            store.dispatch('patientInfos/setafteInfo',signDaa);
                        }else{
                            console.log('有签到  没有改变')
                            return ''
                        }
                        
                       
                    }
                     // 签到体重有大偏差
                    else if(dataBody.taskType==="PreWeightDiff"){
                        const data=new Date()
                        ElNotification({
                            title: dataBody.taskSender,
                            dangerouslyUseHTMLString: true,
                            message: dataBody.taskPara,
                            type: 'warning',
                            duration: 10000,
                            onClose:()=>{
                            console.log(dataBody.code,'0000')
                            // 看看是否是自己关闭的
                            const jg= jgTime3(data)
                            // 自动关闭的 
                            if(jg>=10){
                                console.log('10秒自动关闭')
                            }else{
                                console.log('手动关闭')
                            }
                            }
                            
                        })
                        
                       
                    }
                    // ca登录完成
                    else if (dataBody.taskType === "CaLoginCompleted") {
                      // console.log('aaaa')
                      ElMessage.success(dataBody.taskPara || '登录成功');
                      store.commit('socketMessage/ADD_WEBSOCKET_MESSAGE', dataBody.taskType);
                    }
                    // 需要弹出警告框的消息
                    else if(taskTypeByElMessageBoxs.includes(dataBody.taskType)){
                     ElMessageBox.confirm(
                        dataBody.taskPara,
                        dataBody.taskSender,
                        {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                        closeOnClickModal: false,
                        }
                    )
                        .then(() => {
                        })
                        .catch(() => {
                        })
                    }
                    else{ //其他系统消息
                        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('手动关闭')
                            }
                            }
                            
                        })
                    }
                    
                }
                else if(dif>=0){
                    // console.log('----',dif)
                    // console.log(msg.substring(dif+5, msg.length))
                    const pas=msg.substring(dif+5, msg.length)
                    proxy.mittBus.emit('openDify',pas);
                }
                
            }

        };
        } catch (error) {
            console.log(error);
        }
    };
    //初始化
    const sourceInit = () => {
        console.log('初始化see')
        if (!source.value|| source.value.readyState === 2) {
        creatSource();
        }
    };
    //  关闭 WebSocket
    const closeSource = () => {
        console.log('断开')
        source.value?.close();
    };
    onMounted(()=>{
        sourceInit()
    })
    // 取消订阅
    onBeforeMount(()=>{
        closeSource()
    })
    //重连
    const reconnectSSE = () => {
        try {
            closeSource();
            source.value= null;
            creatSource();
        } catch (e) {
            console.log(e);
        }
    };
   // 页面卸载时
    onUnmounted(() => {
        console.log('页面卸载Tttp')
        closeSource()
    });
  </script>
  