<template>
    <div id="container-terminal"></div>
</template>


<style scoped>
body{
    padding: 0%;
    margin:5px;
    background-color: #000;
    height: 100%;
}
#container-terminal{
    width:100%;
    height:85%;
    margin:0;
    padding:0;
}


</style>


<script setup lang="ts">
import { Terminal } from 'xterm'
import 'xterm/css/xterm.css'
import {useRoute,useRouter} from "vue-router"
import {message} from "../../../utils/message"
import {onMounted,onUnmounted} from "vue"
const route = useRoute()
const router = useRouter()
onMounted(() =>{
    checkProtocol()
    stopHeartBeat()
})

let heartbeatTimerId = null;
function startHeartBeat(data:any){
    heartbeatTimerId = setInterval(() => {
        data.send("")
    },10000);
}
function stopHeartBeat(){
    clearInterval(heartbeatTimerId)
}
//判断协议
function checkProtocol(){
    if(window.location.protocol === "https:" &&
         String(route.query.server_addr).split(":")[0]!== "ws"){
       console.log("当前页面使用的是https协议")
       router.back(); 
    }else{
        console.log("当前页面使用的是HTTP协议")
        function resizeTerminal(term:any){
            const container = document.getElementById("container-terminal")
            if(!container) {
                console.error("Container terminal not found")
                return;
            }
            const style = window.getComputedStyle(container)
            const charWidth = parseInt(style.getPropertyValue("--xterm-char-width"),10) || 10;
            const charHeight = parseInt(style.getPropertyValue("--xterm-char-height"),10) || 20;
            const width = container.offsetWidth;
            const height = container.offsetHeight;
            const cols = Math.floor(width /charWidth);
            const rows = Math.floor(height / charHeight);
            term.resize(cols,rows);
        }
        function getQueryVal(variable:any){
            const query = window.location.search.substring(1);
            const vars = query.split("&");
            for(let i = 0;i< vars.length;i++){
                const pair = vars[i].split("=");
                if(pair[0] === variable){
                    return pair[1]
                }
            }
            return false;
        }
        let  token = route.query.token;
        if(!token){
            throw new Error("token not found")
        }
        let server_addr = route.query.server_addr
        if(!server_addr){
            throw new Error("server_addr not found")
        } 
        let command = getQueryVal("cmd")
        if(!command) {
            command = "/bin/bash"
        }
        let websocket = new WebSocket(
            "ws://" + server_addr + "/console/" + "exec/" + token + "," + window.btoa(command)
        )
        websocket.onerror = function(event:any){
            console.error("WebSocket error:",event)
            message("网络波动",{type:"error"});
            router.back();
        }
        websocket.onopen = function(){
            let term = new Terminal({
                cols: 300,
                rows:30,
                cursorBlink:true
            })
            console.log("打开终端")
            startHeartBeat(websocket)
            term.onData(function(data:any){
                websocket.send(data)
            })
            term.onTitleChange(function(title:any){
                document.title = title
            })
            term.open(document.getElementById("container-terminal")!);
            resizeTerminal(term);
            window.addEventListener("resize",()=>{
                resizeTerminal(term)
            })
            websocket.onmessage = function (evt) {
                term.write(evt.data)
                console.log("发送消息",evt)
            }
            websocket.onclose = function(){
                term.write("session terminated");
                term.dispose() 
            }
            websocket.onerror = function (evt){
                if(evt) {
                    message("网络波动",{type:"error"})
                    router.back()
                }
            }



        }
        





    }
}







</script>