<template>
  <div  class="go-title-03" ref="vChartRef" id="mars3dContainer"></div>
</template>

<script setup lang="ts">
import { PropType, toRefs, ref, watch, onMounted, nextTick } from 'vue'
import { CreateComponentType } from '@/packages/index.d'
import { useChartDataFetch } from '@/hooks';
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
import { isArray } from '@/utils'
import * as mars3d from "mars3d"

const props = defineProps({
  chartConfig: {
    type: Object as PropType<CreateComponentType>,
    required: true
  }
})

const { w, h } = toRefs(props.chartConfig.attr)
const {
  borderColor,
  mapOptions,
} = toRefs(props.chartConfig.option)

let map: mars3d.Map; // 地图对象
const isFirstLoad = ref(true);
const vChartRef = ref<HTMLElement>()
let graphicLayer;
const initMap = (newData: any) => {
  // 第一次加载
  if(isFirstLoad.value){
    map = new mars3d.Map(vChartRef.value, newData);
  }else{ // 之后更新
    map.setSceneOptions(newData.scene);
  }
  isFirstLoad.value = false;
  graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer)
}
 
const stopWatch = watch(
  () => props.chartConfig.option.mapOptions,
 async option => {
  let options = JSON.parse(JSON.stringify(props.chartConfig.option.mapOptions))
    await nextTick();
    initMap(options);
  },
  {
    immediate: true,
    deep: true
  }
)

const myWebSocket = ref();
const lockReconnect = ref(false);
const myWebSocketTimer = ref();

function websocketReconnect() {
  if (lockReconnect.value) {
    // 是否已经执行重连
    return;
  }
  lockReconnect.value = true;
  // 没连接上会一直重连，设置延迟避免请求过多
  let tt;
  tt && clearTimeout(tt);

  tt = setTimeout(function () {
    initWebSocket();
    lockReconnect.value = false;
  }, 120000);
}
function initWebSocket() {
  if ('WebSocket' in window) {
    myWebSocket.value = new WebSocket('ws://111.36.45.20:18088/uav/ws/v1/admin/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50VXNlciI6IlRLNHp5OTMyME1tS3BzdE9zVkpmdDlXanlKMjhBSThKVnV2OU55UjU1Vmw3WWptVUFZUCsveVV3eU1PaUE1V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1B1UmNQZXR3cVVWbGk1dU9vWlBJSXRWbjc1UjlzdHpneHNCeW1JdUhjSDJsWmdLSkhhUmpTWlE4cEQxRlIzUzZZeGtSWDlIa3lvUHE4S3lZNktGckREUW9OanJJVTEvQTg1M0cydyswaEl0QXdOQWZNaXdBbUMvbE1zLytBRk04cm5UcFVCdU9LYnNTSnBxanAzT1k2TitQZVFSZ3pxN1VJcnVlWFBMRXVjQkh4MXRpZkdMZXcvbENGa1pVMDAxNlBWcTNFMDl4TTZha0xLRExTUVcyU1gzZVRxcitVaExkWllvM1RqZEM1NVJ5OW1lZDZTSFNPbWxwcURSaTBvRnZyVXRyL0N4UExwaG1HK0RKd2oyazVHdFFkanJoNkF5RGlpWm5xejFNREFlczZvVkVhUW81MFpkSE5FRU16a25xcUZCWWY3eU5PTVFvOVg4dTdIV2dLZWFndGdjc21DZ1pqVmIrekFsTWpLMk1uSzZGQTY4TlYxV3kxZU41eHp4ZUpySnFoOFBHVHJrMUdPUmQzTjJFdTZOTVdXSzVPVDdWNmNQZzFtMm1WNFNIdnphSnBCYUp0dCs5dFhibkdCNThHOEFUV0g2Um5WRVFWeW1UTGhHK2I3UmE5Q0ZkaWMzWm0yams3K0VROU5LRWxRVWd0UkxhTFJJUnlvZXUzOXhnUWt2dVMvOXA2NHJzc1diUHFoRGw2OHlzK0luRFBIaEVKcFkxRk16aDlWcmZxY290OFJwMlNqbXI2clVOM25sVGpLYzRKR08yakZOTVB4ZXpzaFdsdHpKVjhZeGxJZ0tnZEtPT0kySm8yUTVhbkYxSTRtN01jQ2ZQIiwiZXhwIjoxNzQyNzg0MjU1fQ.p5g59OlxRrof3q-mRXErhyP21f3wkIpeSz3FNaJUGR8');
    myWebSocket.value.onopen = function () {
      if (myWebSocketTimer.value) {
        clearInterval(myWebSocketTimer.value);
      }
      webSocketHeart();
    };

    myWebSocket.value.onmessage = function (evt) {
      const data = JSON.parse(evt.data);
      createListeningEvent(data);
    };
    myWebSocket.value.onclose = function () {
      // 如果断开则重新连接
      websocketReconnect();
    };
  } else {
    alert('您的浏览器不支持 WebSocket!');
  }
}

function webSocketHeart() {
  //长连接心跳检测
  let total = 1;
  myWebSocketTimer.value = setInterval(function () {
    if (myWebSocket.value) {
      total = total + 1;
    }
  }, 30000);
}
const createListeningEvent = (value) => {
  if(value.type == 1 && value.isUavOn == 1){
    handlerAddEntity(value.data)
  }
};
// 添加Entity
const handlerAddEntity = (data) => { 
  let graphicOptions = {
    id: data.siteId,
    position: [parseFloat(data.longitude), parseFloat(data.latitude)],
    style: {
      image: '@/assets/images/chart/equipment/wurenji.png',
      clampToGround: true,
      scale: 0.5,
    }
  }

  let graphic = graphicLayer.getGraphicById(data.siteId);

  if(graphic){
      graphicLayer.removeGraphic(graphic);
      graphic = new mars3d.graphic.BillboardEntity(graphicOptions);
      graphicLayer.addGraphic(graphic);
  }else{
      graphic = new mars3d.graphic.BillboardEntity(graphicOptions);
      graphicLayer.addGraphic(graphic);
  }
}
onMounted(() => {
  stopWatch();
  initWebSocket();
});
</script>

<style lang="scss" scoped>
@include go('title-03') {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center; 
  width: v-bind('w');
  height: v-bind('h');
  border: 1px solid v-bind('borderColor')
}
</style>
