<template>
    <div class="uav-container">
        <div class="title">
            航飞实景
            <div class="switch-button">
                <a-switch v-model:checked="uavLayer.checked" @change="handlerLayerButtonClick" />
            </div>
        </div>
        <div class="uav-list-container">
            <div class="uav-item" v-for="(item,index) in list">
                <div class="name">{{item.model}}</div>
                <div class="phone">{{item.account}}</div>
                <div class="play" @click="handlerPlayVideo(item);toPosition(item);"><PlayCircleOutlined /></div>
                <div class="position" @click="toPosition(item)"><EnvironmentOutlined /></div>
            </div>
            <div class="uav-empty" v-if="list.length == 0">
                <img src="/videosupervision/empty.png" alt="">
                <p>暂无无人机巡航</p>
            </div>
        </div>
        
        <div  v-show="isShowPlayer">
            <div class="close-video-button" @click="closePlayer">
                <CloseOutlined />
            </div>
            <video
                class="video-container"
                id="player-container-id"
                width="235px"
                height="178px"
                autoplay
                preload="auto"
                playsinline
                webkit-playsinline
            ></video>
        </div>
    </div>
</template>
<script lang="ts" setup>
import {PlayCircleOutlined,EnvironmentOutlined,CloseOutlined} from "@ant-design/icons-vue"
import {ref,defineEmits} from 'vue';

const uavLayer = ref({
        lable:"航飞区域",
        value:["uavlayer"],
        checked:true,
})
const checked = ref<Boolean>(true);

const emits = defineEmits(["toPosition","handlerUpdateUavLayerData","handlerLayerButtonClick"])


function handlerLayerButtonClick(item){
    uavLayer.value.checked = item;
    emits("handlerLayerButtonClick",uavLayer.value);
}

function toPosition(item){
    emits("toPosition",[item.lng,item.lat]);
}

function playVideo(item){

}

function controlUavLayer(){

}



const uavList = ref()
// 创建WebSocket
  // socket参数
  const WS_URL = "ws://221.2.83.254:9002/ws"
  let socket =  null
  let timeout =  10 * 1000// 45秒一次心跳
  let timeoutObj = null  // 心跳心跳倒计时
  let serverTimeoutObj = null // 心跳倒计时
  let timeoutnum = 10000 // 断开 重连倒计时
  let lockReconnect= false // 防止
  function initWebSocket() {
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    let wsUrl = WS_URL;
    window.websocket = new WebSocket(wsUrl);
    window.websocket.onopen = websocketonopen;
    window.websocket.onerror = websocketonerror;
    window.websocket.onmessage = setOnmessageMessage;
    window.websocket.onclose = websocketclose;
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    // window.onbeforeunload = that.onbeforeunload
  }
  function start() {
    // console.log("start");
    //清除延时器
    timeoutObj && clearTimeout(timeoutObj);
    serverTimeoutObj && clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(() => {
      if (window.websocket && window.websocket.readyState == 1) {
        //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        window.websocket.send("heartBath");
      } else {
        reconnect();
      }
      //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
      serverTimeoutObj = setTimeout(() => {
        window.websocket.close();
      }, timeout);
    }, timeout);
  }
  function reset() {
    // 重置心跳
    // 清除时间
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    // 重启心跳
    start();
  }
  // 重新连接
  function reconnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    timeoutnum && clearTimeout(timeoutnum);
    timeoutnum = setTimeout(() => {
      initWebSocket();
      lockReconnect = false;
    }, 30000);
  }
  async function setOnmessageMessage(event) {
    // console.log(event.data, "获得消息");
    reset();
    
    // 自定义全局监听事件
    window.dispatchEvent(
      new CustomEvent("onmessageWS", {
        detail: {
          data: event.data,
        },
      })
    );
  }
  function websocketonopen() {
    //开启心跳
    start();
    console.log(
      "WebSocket连接成功!!!" + new Date() + "----" + window.websocket.readyState
    );
  }
  function websocketonerror(e) {
    closeWebSocket()
    console.log("WebSocket连接发生错误,重启socket");
    console.log('Error:',e)
    
  }
  function websocketclose(e) {
    window.websocket.close();
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    console.log("WebSocket连接关闭,重启socket");
    reconnect();
  }
  function websocketsend(messsage) {
    window.websocket.send(messsage);
  }
  function closeWebSocket() {
    // 关闭websocket
    window.websocket.close();
  }
  initWebSocket();



// 处理返回数据
  
function isJson(str){
if (typeof str == 'string') {
        try {
        var obj = JSON.parse(str);
    // 等于这个条件说明就是JSON字符串 会返回true
        if (typeof obj == 'object' && obj) {
            return true;
        } else {
        //不是就返回false
            return false;
        }
        } catch (e) {
        return false;
        }
    }
    return false;
}
function getSocketData(evt){
if (isJson(evt.detail.data)){
    let obj = JSON.parse(evt.detail.data);
    if (obj != "close") {
        if (obj != "" && obj.ip) {
        isAddUav(obj);
        }
    } 
    }else if(evt.detail.data.match("close")){
    let ip = evt.detail.data.split(",")[0];
    isUAVHave(ip);
    }
}

const list = ref([]);


let currentUav = null;

function isUAVHave(ip){
    // 如果匹配到IP就删除掉
    list.value.forEach((item,index)=>{
        if(item.ip == ip){
            list.value.splice(index,1);
        }
    })
}

function isAddUav(obj){
    let idx = null;
    let uav = list.value.find((item,index)=>{
        if(item.ip == obj.ip){
            idx = index;
        }
        return item.ip == obj.ip
    })
    if(!uav){
        list.value.push(obj);
    }else{
        list.value[idx] = obj;
    }
    if(list.value?.length>0){
        emits("handlerUpdateUavLayerData",list.value);
    }
}


// 监听websoket推送数据
window.addEventListener("onmessageWS", getSocketData);

// 播放视频监控
const isShowPlayer = ref<Boolean>(false);

let player = null;
function closePlayer(){
    isShowPlayer.value = false;
    // player = null;
}
function handlerPlayVideo(item){
    let phone = item.account;
    if(phone){
        isShowPlayer.value = true;
        window.websocket.send(phone);

        if (player) {
                player.src("http://live.hopetrytech.com/live/" + phone + ".flv");
            } else {
                player = TCPlayer("player-container-id", {});
                player.src("http://live.hopetrytech.com/live/" + phone + ".flv");
            }

        setTimeout(function(){
            
        },1000)
    }else{

    }

}




</script>

<style type="less" scoped>

.uav-container{
    width: 418px;
    height: 300px;
    background:#041B36;
    position: relative;
    &::before{
        content:"";
        height:70%;
        width:50px;
        position:absolute;
        bottom:10px;
        left:10px;
        background:url("/videosupervision/main-left.png");
        background-size:100% 100%;
    }
    &::after{
        content:"";
        height:70%;
        width:50px;
        position:absolute;
        bottom:10px;
        right:10px;
        background:url("/videosupervision/main-right.png");
        background-size:100% 100%;
    }
    .title{
        width:100%;
        height:40px;
        background-image:url("/videosupervision/title.png");
        background-size:100% 100%;
        line-height:40px;
        text-indent:18px;
        font-size:18px;
        font-weight:bold;
        color:#fff;
    }
    .switch-button{
        float:right;
        margin-right:20px;
    }
    .uav-list-container{
        width:100%;
        height: calc( 100% - 60px);
        overflow:auto;
        padding:20px 20px;
        position:relative;
        z-index:999;
        .uav-empty{
            width:100%;
            height:100%;
            text-align:center;
            color:#999;
            img{
                width:120px;
                margin:40px 0px 18px 0px;
            }
        }
        .uav-item{
            width:100%;
            height:40px;
            padding:0px 15px;
            line-height:40px;
            color:#f1f1f1;
            display:flex;
            background:rgba(0,0,0,0.2);
            &:hover{
                background:rgba(0,0,0,0.4);
            }
            div{
                flex:1;
            }
            .position{
                max-width:30px;
                cursor:pointer;
            }
            .play{
                max-width:30px;
                cursor:pointer;
            }
        }
    }

    .video-container{
        width: calc( 100% - 30px);
        height: calc( 100% - 70px);
        position:absolute;
        margin:15px;
        top:40px;
        right:0px;
        z-index:1000;
        background:#041B36;
        .video-contain {
            width: 100%;
            height: 100%;
        }
        
    }
    .close-video-button{
        position:absolute;
        top:40px;
        right:10px;
        background:rgba(0,0,0,0.3);
        z-index:100100;
        color:#fff;
        padding:10px;
        cursor:pointer;
        &:hover{
            color:#408eff;
        }
    }
}   
</style>