<template>
    <div class="chat_room"
         ref="roomRef"
         @click="dialog = true">
        <div class="count">
            {{ userSize }}
        </div>
    </div>

    <emr-chat-box
            v-if="dialog"
            ref="dialogRef"
            :current-editor-user="props.currentEditorUser"
            @closed="dialog = false"
            :user-list="userList"
            :sid="sid"/>


    <el-dialog v-model="errDialog" title="与服务器断开连接"
               :show-close="false"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
        <div v-loading="errDialog"
             element-loading-text="正在尝试重新连接..."
             style="width: 100%;height: 400px"/>

    </el-dialog>

</template>

<script setup name='EmrWebSocket' lang="ts">
import {stringIsBlank} from "@/utils/blank-utils";
import store from "@/store";
import {ref, defineProps, onMounted, nextTick, computed, onBeforeUnmount} from 'vue'
import {xcMessage} from '@/utils/xiaochan-element-plus'
import {getRoomPeople, sendAMessage} from '@/api/zhu-yuan-yi-sheng/emr-socket'
import {ElNotification} from "element-plus";
import EmrChatBox from "@/components/zhu-yuan-yi-sheng/emr/web-socket/EmrChatBox.vue";
import {$ref} from "vue/macros";

const props = defineProps({
    patInfo: {
        type: Object,
        default: null
    },
    currentEditorUser: {
        type: Object,
        default: null
    }
})
const roomRef = ref<HTMLElement | null>(null)

const dialog = ref<boolean>(false)
const errDialog = ref<any>(true)
const userMap = ref<any>({})
const dialogRef = ref(null)

const SOCKET_URL = import.meta.env.VITE_SOCKET_URL

let webSocket = null
let userData = store.state.user.info
let sid = $ref(null)

const onmessageFunc = {
    "connect": async (data) => {
        await queryTheNumberOfPeopleInTheRoom()
        xcMessage.success('连接成功')
    },
    "connectToJoin": async (val) => {
        await queryTheNumberOfPeopleInTheRoom()
        let userInfo = userMap.value[val]
        ElNotification({
            type: 'success',
            title: '有新的连接加入',
            dangerouslyUseHTMLString: true,
            message: `<span>姓名：${userInfo.name}</span>
                <br>
                <span>科室：${userInfo.deptName}</span>`
        })
        console.log("连接加入 %s, 数据 %o", val, userMap.value)
    },
    "exitEmrEditor": async (val) => {
        let userInfo = userMap.value[val]
        ElNotification({
            type: 'error',
            title: '有连接退出',
            dangerouslyUseHTMLString: true,
            message: `<span>姓名：${userInfo.name}</span>
                <br>
                <span>科室：${userInfo.deptName}</span>`
        })
        console.log("连接退出 %s，数据 %o", val, userMap.value)
        await queryTheNumberOfPeopleInTheRoom()
    },
    "message": async (val) => {
        if (dialog.value) {
            dialogRef.value.queryJump();
        }
        dialog.value = true
        console.log("接受消息 %o", val)
    },
    "notice": (val) => {
        ElNotification({
            type: 'success',
            title: '查看或编辑',
            message: val
        })
    },
    "closeSoctek": (val) => {
        if (navigator.userAgent.indexOf("Firefox") !== -1 || navigator.userAgent.indexOf("Chrome") !== -1) {
            window.location.href = "about:blank";
            window.close();
        } else {
            window.opener = null;
            window.open("", "_self");
            window.close();
        }
    }
}

const userSize = computed(() => {
    return Object.keys(userMap.value).length
})

const userList = computed(() => {
    return Object.values(userMap.value)
})

const queryTheNumberOfPeopleInTheRoom = async () => {
    userMap.value = await getRoomPeople(sid) as any
}

function initWebSocket(patNo, times) {
    if (stringIsBlank(patNo)) {
        return null
    }

    if ('WebSocket' in window) {
        sid = 'emr_' + patNo.trim() + '_' + times;
        const url = SOCKET_URL + sid + '?userCode=' + userData.code;
        webSocket = new WebSocket(url);
    } else {
        alert('该浏览器不支持websocket!');
        webSocket = 'unsupport';
    }

    webSocket.onopen = async () => {
        errDialog.value = false
    }


    webSocket.onmessage = async function (e) {
        let data = JSON.parse(e.data)
        for (let key in data) {
            onmessageFunc[key](data[key])
        }

    }

    webSocket.onclose = () => {
        errDialog.value = true
        initWebSocket(props.patInfo.inpatientNo, props.patInfo.admissTimes)
    }

}

const medicalRecordSwitching = async (name) => {
    await sendAMessage(sid, "notice", name)
}


let documentSocket = null
let documentSid = null
const documentChange = (id) => {
    documentSid = 'documentEmr_' + id + '_' + userData.code
    if (documentSocket != null) {
        documentSocket.close()
        documentSocket = null
    } else {
        if ('WebSocket' in window) {
            initDocumentSocket()
        } else {
            alert('该浏览器不支持websocket!');
            documentSocket = null;
        }
    }
}

const initDocumentSocket = () => {
    if (documentSid == null) return
    let temp = SOCKET_URL + documentSid

    documentSocket = new WebSocket(temp)

    documentSocket.onopen = () => {
        console.log('连接成功')
    }

    documentSocket.onclose = () => {
        initDocumentSocket()
    }

}

const clearDocument = () => {
    if (documentSocket != null) {
        documentSocket.close()
        documentSocket = null
        documentSid = null
    }
}

const clearSocket = () => {
    if (webSocket != null) {
        webSocket.close()
        webSocket = null
    }
}

onMounted(async () => {
    await nextTick()
    initWebSocket(props.patInfo.inpatientNo, props.patInfo.admissTimes)
})

onBeforeUnmount(() => {
    clearDocument()
    clearSocket()
})

defineExpose({
    medicalRecordSwitching,
    documentChange,
    clearDocument,
    clearSocket
})

</script>

<style scoped lang="scss">
.chat_room {
  bottom: 0;
  right: 0;
  position: absolute;
  width: 40px;
  height: 40px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  background-color: rgb(0 0 0 / 63%);
  border-radius: 9px;
  cursor: all-scroll;

  .count {
    width: 25px;
    text-align: center;
    line-height: 25px;
    background-color: rgba(255, 255, 255, 0.48);
    border-radius: 12px;

    position: relative;

  }

}

</style>
