<template>
    <div class="box">
      <!-- <div class="close-button" @click="close">
          <i class='el-icon el-icon-close'></i>
      </div> -->
      <div class="box-container">
          <div class="flex fc-w fz-16 column" style="margin:10px">
            <div>当前在线总人数：{{ listDataInfo.onlineCount }}人</div>
          </div>
          <div class="table-body">
              <div class="item flex jc-sb" v-for="(item,index) in listDataInfo.onOffLineInfo" :key="index">
                  <div>{{item.time}}</div>
                  <div>{{ item.name }}{{ item.typeName }}了</div>
              </div>
          </div>
      </div>
    </div>
  </template>
  
<script>
import { mapState,mapGetters } from "vuex";   
import axios from "axios";
import { getMethodCommon } from '@/api/common.js';
let BASE_URL = process.env.VUE_APP_BASE_API;
import AppConfig from '../../../../public/config/app.json'
import { parse } from '../lib/handleGeojson.js';
import * as turf from '@turf/turf'
import { isJson } from "../../../utils/index";

export default {
    name: 'monitorbox',
    computed: {
    ...mapGetters([
      
    ]),
    //trtc
    ...mapState({
      websocket:state=>state.Emergency.listenWebSocket,
    }),
  },
    props:['globalmap',"showOnlineUser"],
    data(){
        return{
            listDataInfo:[],
            pointData:[],
            markGraphicLayer: null,
            markGraphicLayerArr:[],
            startPoint:null,
            endPoint:null,
            pathPointGraphicLayer:null,
        }
    },
    watch:{
        showOnlineUser:{
            handler(newVal,oldVal){
                if(this.markGraphicLayer){
                    this.markGraphicLayer.show = newVal;
                }
            },  
            immediate:true
        }
    },
    created(){
        this.getOnLineInfo()
        this.initWebSocket()
        window.addEventListener("onmessageWS", this.getSocketData);
        setInterval(()=>{
            this.pointData = []
            let arr = ['人员信息','对讲机信息']
            arr.forEach(item =>{
                this.getPointer(item)
            })
        },120000)
    },
    mounted(){
        window.videoCall = this.videoCall
        window.designRoute = this.designRoute;
        window.deleteRoute = this.deleteRoute;

        let _this = this;

        _this.getPointer();

        setInterval(function(){
            _this.pointData = []
            let arr = ['人员信息','对讲机信息']
            _this.getPointer("人员信息")
        },5000)

    },
    methods:{
        getSocketData(res){
            let _this = this;
            if (!isJson(res.detail.data)) return;
            let obj = JSON.parse(res.detail.data)
            if(obj.Module){
                _this.pointData = []
                if(obj.Module == '人员信息' || obj.Module == '对讲机信息'){
                    //_this.getPointer(obj.Module)
                }
                if(obj.Module == '上线' || obj.Module == '下线'){
                    _this.getOnLineInfo()
                }
                
            }
        },
        close(){
            this.markGraphicLayerArr.forEach(item =>{
                this.markGraphicLayer.removeGraphic(item)
            })
            this.$emit('close')
        },
        videoCall(phone){
            let userId = localStorage.getItem("userName") || ''
            if(userId && phone){
                // let wind = window.open("https://ssl.hopetrytech.com:9233/#/userID="+userId+"&callUserID="+phone, "视频通话", "location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=640,height=460");
                let wind = window.open("https://ssl.hopetrytech.com:9233?userID="+userId+"&callUserID="+phone, "视频通话", "location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=640,height=460");
                wind.onload = function(){
                    wind.document.title = "视频通话";
                }
            }
            else{
                this.$message({
                        type:"warning",
                        message:"系统错误，调用视频通话接口失败"
                    })
            }
            
            // window.navigator.mediaDevices.enumerateDevices().then(devices => {
            //     let isSuppertVideo = 0;
            //     for(let i=0;i<devices.length;i++){
            //         if(devices[i].kind =="videoinput"){
            //             isSuppertVideo++;
            //         }
            //     }
            //     if(isSuppertVideo>0){
            //         let wind = window.open("https://ssl.hopetrytech.com:9233/#/?userID="+localStorage.getItem("userName")+"&callUserID="+phone, "视频通话", "location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=640,height=460");
            //         wind.onload = function(){
            //           wind.document.title = "视频通话";
            //         }
            //     }else{
            //         this.$message({
            //             type:"warning",
            //             message:"当前设备暂不支持视频通话！"
            //         })
            //     }
            // }) 
        },
        getOnLineInfo(){
            getMethodCommon("/FireManagement/GetOnOffLineInfo").then(res =>{
                this.listDataInfo = res.data
            })
        },
        getPointer(type){
            getMethodCommon("/FireManagement/GetPointByType",{type:type}).then(res =>{
                res.data.forEach(item =>{
                    this.pointData.push(item)
                })
                this.addLayerPoint()
                console.log('this.markGraphicLayerArr',this.markGraphicLayerArr)
            })
        },  
        addLayerPoint(){
            if(this.markGraphicLayer == null){
                this.markGraphicLayer = new mars3d.layer.GraphicLayer();
                this.globalmap.addLayer(this.markGraphicLayer);
            }
            this.markGraphicLayerArr.forEach(item =>{
                this.markGraphicLayer.removeGraphic(item)
            })

            this.markGraphicLayer.clear();

            this.markGraphicLayerArr = [] 
            this.pointData.forEach((item,index)=>{
                let graphic = new mars3d.graphic.BillboardEntity({
                    position: [item.lng,item.lat],
                    style: {
                        image: "/img/jiuyuanrenyuan.png",
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        clampToGround:true,
                        scale:0.5,
                        label: {
                            text: "",
                            font_size: 14,
                            color: "#ffffff",
                            pixelOffsetY: 10,
                            distanceDisplayCondition: true,
                            distanceDisplayCondition_far: 500000,
                            distanceDisplayCondition_near: 0
                        }
                    },
                    pointerEvents: true
                })
                this.markGraphicLayerArr.push(graphic)
                this.markGraphicLayer.addGraphic(graphic);
                let graphicWinodw = new mars3d.graphic.DivGraphic({
                    position: [item.lng,item.lat],
                    style: {
                        html: `<div class="marsTiltPanel marsTiltPanel-theme-blue" style="font-size:12px;">
                    <div class="marsTiltPanel-wrap">
                        <div class="area">
                            <div class="arrow-lt"></div>
                            <div class="b-t"></div>
                            <div class="b-r"></div>
                            <div class="b-b"></div>
                            <div class="b-l"></div>
                            <div class="arrow-rb"></div>
                            <div class="label-wrap">
                                <div class="title">人员信息</div>
                                <div class="label-content">
                                    <div class="data-li">
                                        <div class="data-label">人员名称：${item.name}</div>
                                    </div>
                                    <div class="data-li">
                                        <div class="data-label">电话号码：${item.phone}</div>
                                        <div class="data-value"><span id="lablYeWei"  class="label-num"></span><span class="label-unit"></span>
                                        </div>
                                    </div>
                                    <div class="data-li">
                                        <div class="data-value">
                                            <span class="label-tag data-value-status-2" title="视频通话" onclick="videoCall('${item.phone}')">视频通话</span></div>
                                            <span id="lablSBZT1" onclick="designRoute('${item.createId}');" class="label-tag data-value-status-1" title="人员动态">路线高亮</span>
                                            <span id="lablSBZT1" onclick="deleteRoute('${item.createId}');" class="label-tag data-value-status-2" title="清除路线">路线隐藏</span>
                                            
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="b-t-l"></div>
                        <div class="b-b-r"></div>
                    </div>
                    <div class="arrow" ></div>
                </div>`,horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
                        scaleByDistance: new Cesium.NearFarScalar(1000, 0.7, 8000, 0.2),
                        clampToGround: true,
                        offsetY: -60,
                    },
                    pointerEvents: true // false时不允许拾取和触发任意鼠标事件，但可以穿透div缩放地球
                })
                this.markGraphicLayerArr.push(graphicWinodw)
                this.markGraphicLayer.addGraphic(graphicWinodw);
            })
        },
        deleteRoute(){
            if(this.pathPointGraphicLayer){
                this.pathPointGraphicLayer.clear();
            }
        },
        designRoute(userId){
            axios({
                method:"get",
                url:BASE_URL+"/Patrol/LoadUserNavigationByUserId",
                params:{
                    id:userId
                },
                headers:{
                    "X-Token":localStorage.getItem("X-Token")
                }
            }).then(res=>{
                if(res.data.code == 200){
                    if(res.data.data){
                        this.startPoint = res.data.data.startLng+","+res.data.data.startLat;
                        this.endPoint = res.data.data.endLng+","+res.data.data.endLat;
                        this.getRoutePath();
                    }else{
                        this.$message({
                            type:"warning",
                            message:"当前人员暂无规划地",
                        })
                    }
                }
            })
        },
        drawPoint(type, lng, lat, z) { // 绘制起点、终点
            let image = null;
            if (type == "start") {
                image = "/img/route-start.png"
            } else {
                image = "/img/route-end.png"
            }
            var graphic = new mars3d.graphic.BillboardEntity({
                position: [lng, lat, z],
                style: {
                    image: image,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    clampToGround: true
                },
                attr: { remark: type == 'start'?'起点':'终点' }
            })
            this.pathPointGraphicLayer.addGraphic(graphic) // 还可以另
        },
         getRoutePath(){ // 获取路线数据
            if(this.startPoint&&this.endPoint){
                let startCoor =  this.startPoint.split(",");
                let endCoor = this.endPoint.split(",");
                axios({
                    method: 'get',
                    url: AppConfig[localStorage.getItem('areaName')].baseUrl+'/api/FirePrevention/LoadRoad',
                    params: {
                        startlng: parseFloat(startCoor[0]),
                        startlat: parseFloat(startCoor[1]),
                        endlng: parseFloat(endCoor[0]),
                        endlat: parseFloat(endCoor[1]),
                    }
                }).then(data => {
                    if (data.data.data.length > 0) {
                        
                        let LineString = data.data.data[0].route;

                        if(LineString == null || LineString == "null"){
                            
                        }else{
                            let _this = this;
                            setTimeout(function () {
                               _this.drawRoutePath(parse(LineString));
                                // designPath(parse(LineString));
                            }, 1000)
                        }
        
                    }else{
                        
                    }
                })
            }else{

            }
        },
        drawRoutePath(geojson) { // 绘制路线

            if(this.pathPointGraphicLayer == null){
                this.pathPointGraphicLayer = new mars3d.layer.GraphicLayer();
                this.globalmap.addLayer(this.pathPointGraphicLayer);
            }else{
                this.pathPointGraphicLayer.clear();
            }

           

            if(geojson.type=="LineString"){
                geojson.coordinates = [geojson.coordinates]
            }

            // 虚线部分
            var startCoor = this.startPoint.split(",");
            var endCoor =this.endPoint.split(",");

             if(this.startPoint&&this.endPoint){
                         this.drawPoint("start",parseFloat(startCoor[0]),parseFloat(startCoor[1]),0)
                        this.drawPoint("end",parseFloat(endCoor[0]),parseFloat(endCoor[1]),0)
                    }else{
                        this.$message({
                            type:"warning",
                            message:"当前人员暂无规划地",
                        })
                    }


            // 起始点坐标
            var startCoorArr = [parseFloat(startCoor[0]), parseFloat(startCoor[1])]
            // 终点坐标
            var endCoorArr = [parseFloat(endCoor[0]), parseFloat(endCoor[1])]

            var startTurfPoint = turf.point(startCoorArr);
            var endTurfPoint = turf.point(endCoorArr);

            // 起始路线部分
            var startPath = [];
            geojson.coordinates[0].forEach((item, index) => {
                startPath.push(turf.point([item[0], item[1]]));
            })

            var startTurfPath = turf.featureCollection(startPath);
            var startNearestPoint = turf.nearestPoint(startTurfPoint, startTurfPath);

            var startNearestPointLngLat = null;
            if (startNearestPoint) {
                startNearestPointLngLat = startNearestPoint.geometry.coordinates;
                var graphic = new mars3d.graphic.PolylineEntity({
                positions: [
                    startCoorArr,
                    startNearestPointLngLat,
                ],
                style: {
                    width: 5,
                    clampToGround: true,
                    materialType: mars3d.MaterialType.PolylineDash,
                    materialOptions: {
                    color: Cesium.Color.YELLOW,
                    dashLength: 8.0
                    }
                },
                attr: { remark: "虚线" }
                })
                this.pathPointGraphicLayer.addGraphic(graphic)
            }

            // 终点路线部分
            var endPath = [];
            geojson.coordinates[geojson.coordinates.length - 1].forEach((item, index) => {
                endPath.push(turf.point([item[0], item[1]]));
            })
            var endTurfPath = turf.featureCollection(endPath);
            var endNearestPoint = turf.nearestPoint(endTurfPoint, endTurfPath);

            var endNearestPointLngLat = null;
            if (endNearestPoint) {
                endNearestPointLngLat = endNearestPoint.geometry.coordinates;
                var graphic = new mars3d.graphic.PolylineEntity({
                positions: [
                    endCoorArr,
                    endNearestPointLngLat,
                ],
                style: {
                    width: 5,
                    clampToGround: true,
                    materialType: mars3d.MaterialType.PolylineDash,
                    materialOptions: {
                    color: Cesium.Color.YELLOW,
                    dashLength: 8.0
                    }
                },
                attr: { remark: "虚线" }
                })
                this.pathPointGraphicLayer.addGraphic(graphic)
            }

            // 漫游数据
            var tripArr = [];
            // 实线路线部分
            geojson.coordinates.forEach((item, index) => {
                tripArr = tripArr.concat(item);
                // var graphic = new mars3d.graphic.PolylineEntity({
                //   positions: item,
                //   style: {
                //     width: 5,
                //     clampToGround: true,
                //     // materialType: mars3d.MaterialType.PolylineDash,
                //     materialOptions: {
                //       color: Cesium.Color.CYAN,
                //       dashLength: 8.0
                //     }
                //   },
                //   attr: { remark: "最优路线" }
                // })
            })

            var graphic = new mars3d.graphic.PolylineEntity({
                positions: tripArr,
                style: {
                width: 5,
                clampToGround: true,
                materialType: mars3d.MaterialType.LineFlow,
                materialOptions: {
                    color: Cesium.Color.CYAN,
                    image: "/img/line-colour.png",
                    speed: 10
                }
                },
                attr: { remark: "示例13" }
            })
            this.pathPointGraphicLayer.addGraphic(graphic)

            this.pathPointGraphicLayer.flyTo();

            this.tripFlyArray = [];
            tripArr.forEach((item, index) => {
                if (index % 20 == 0) {
                    this.tripFlyArray.push(item);
                }
            })
        
        },
        initWebSocket() {
            let _this = this;
            if ("WebSocket" in window) {
                // 打开一个 web socket
                var ws = new WebSocket("ws://221.2.83.254:7002/ws");
                var heartCheck;
                ws.onopen = function () {
                    //Web Socket 已连接上，使用 send() 方法发送数据
                    console.log('WEBSOCKET-ONLINE')
                    heartCheck = setInterval(function() {
                        ws.send('HeartBeat');
                    }, 5000);
                };
                ws.onmessage = function (evt) {
                    
                    clearInterval(heartCheck);
                    heartCheck = setInterval(function() {
                        ws.send('HeartBeat');
                    }, 5000);

                    let obj = JSON.parse(evt.data)
                   
                    if(obj.Module){
                        _this.pointData = []
                        if(obj.Module == '人员信息' || obj.Module == '对讲机信息'){
                            _this.getPointer(obj.Module)
                        }
                        if(obj.Module == '上线' || obj.Module == '下线'){
                            _this.getOnLineInfo()
                        }
                        
                    }
                };
                ws.onclose = function () {
                    clearInterval(heartCheck);
                    console.log('WEBSOCKET-CLOSED')
                    _this.initWebSocket()
                };
                ws.onerror= function () {
                    clearInterval(heartCheck);
                    console.log('WEBSOCKET-ERROR')
                    _this.initWebSocket()
                };
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        },
    }
}
</script>
  
<style scoped>
/* .box{
    width: 100%;
    height: calc( 100% - 5px);;
    overflow: hidden;
    text-align:left;
    z-index: 99;
} */
/* 隐藏该图表 */
.box{
width: 1px;
height: 1px;
overflow: hidden;
}
.box-name{
    height: 47px;
    line-height: 47px;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
    padding: 0 40px;
    }
.box-title{
     width:100%;
      height:45px;
      overflow: hidden;
      line-height:40px;
      color:#eee;
      text-align: center;
      font-size:14px;
}
.box-container{
    width: calc( 100% - 0px);
    padding:10px 12px;
    height: calc( 100% - 50px);
}
.table-header{
    width: calc( 100% - 10px);
    height:25px;
    color:#fff;
    text-align: center;
}
.table-header div{
    float:left;
    width:25%;
    border-bottom:1px dashed #00FFF0;
    padding-bottom:8px;
}
.table-body{
    width:100%;
    height: calc( 100% - 0px);
    overflow-y: auto;
}

.table-body .item{
    width:100%;
    height:40px;
    background: #00ffee2f;
    font-size:14px;
    text-align: center;
    line-height:40px;
}

.table-body .item:nth-child(2n){
    background:#0099ff50;
}
.close-button{
  position:absolute;
  right:20px;
  top:14px;
  cursor:pointer;
  color:#fff;
  font-weight: bold;
  width:20px;
  height:20px;
  background:#0a58bfcc;
  line-height:20px;
  text-align:center;
}

.table-body .item div{
    float:left;
    width:50%;
    color:#eee;
}

::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb {
    border: 0
}


::-webkit-scrollbar {
    height: 10px;
    width: 10px;
    background: transparent;
    border-radius: 5px
}

::-webkit-scrollbar-thumb {
    padding-top: 100px;
    -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1), inset -1px -1px 0 rgba(0, 0, 0, .07);
    background-color: #797979;
    min-height: 28px;
    border-radius: 4px;
    background-clip: padding-box
}

::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb {
    border: 0
}

::-webkit-scrollbar-thumb:hover {
    -webkit-box-shadow: inset 1px 1px 1px rgba(0, 0, 0, .25);
    background-color: rgba(0, 0, 0, .4)
}

::-webkit-scrollbar-thumb:active {
    -webkit-box-shadow: inset 1px 1px 3px rgba(0, 0, 0, .35);
    background-color: rgba(0, 0, 0, .5)
}

</style>