<template>
  <div
    :class="`go-preview ${chartEditStore.editCanvasConfig.previewScaleType}`"
    @mousedown="dragCanvas"
  >
    <template v-if="showEntity">
      <!-- 实体区域 -->
      <div ref="entityRef" class="go-preview-entity">
        <!-- 缩放层 -->
        <div ref="previewRef" class="go-preview-scale">
          <!-- 展示层 -->
          <div :style="previewRefStyle" v-if="show">
            <!-- 渲染层 -->
            <preview-render-list></preview-render-list>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <!-- 缩放层 -->
      <div ref="previewRef" class="go-preview-scale">
        <!-- 展示层 -->
        <div :style="previewRefStyle" v-if="show">
          <!-- 渲染层 -->
          <preview-render-list></preview-render-list>
          <!-- <button @click="test">测试</button> -->
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
  import { computed, watch, onMounted, ref } from 'vue';
  import { PreviewRenderList } from './components/PreviewRenderList';
  import { getFilterStyle, setTitle } from '@/utils';
  import {
    getEditCanvasConfigStyle,
    getSessionStorageInfo,
    keyRecordHandle,
    dragCanvas,
  } from './utils';
  import { useComInstall } from './hooks/useComInstall.hook';
  import { useScale } from './hooks/useScale.hook';
  import { useStore } from './hooks/useStore.hook';
  import { PreviewScaleEnum } from '@/enums/styleEnum';
  import type { ChartEditStorageType } from './index.d';
  import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
  import { useRoute } from 'vue-router';
  import { EventBus } from '@/utils/eventBus';
  import { websocketEvent, eventCommonHandler } from '@/hooks/eventHandler.hook';

  // const localStorageInfo: ChartEditStorageType = getSessionStorageInfo() as ChartEditStorageType
  const route = useRoute();

  await getSessionStorageInfo();
  const chartEditStore = useChartEditStore() as unknown as ChartEditStorageType;
  setTitle(
    chartEditStore.editCanvasConfig.projectName
      ? `预览-${chartEditStore.editCanvasConfig.projectName}`
      : '',
  );

  const previewRefStyle = computed(() => {
    return {
      overflow: 'hidden',
      ...getEditCanvasConfigStyle(chartEditStore.editCanvasConfig),
      ...getFilterStyle(chartEditStore.editCanvasConfig),
    };
  });

  const showEntity = computed(() => {
    const type = chartEditStore.editCanvasConfig.previewScaleType;
    return type === PreviewScaleEnum.SCROLL_Y || type === PreviewScaleEnum.SCROLL_X;
  });

  useStore(chartEditStore);
  const { entityRef, previewRef } = useScale(chartEditStore);
  const { show } = useComInstall(chartEditStore);

  // 开启键盘监听
  keyRecordHandle();
  watch(
    () => route.fullPath,
    (newValue) => {
      location.reload();
    },
  );
  const createListeningEvent = (value) => {
    chartEditStore.getComponentList.forEach((item) => {
      item.events.interactConfigEvents.forEach((event) => {
        if (event.type == 'websocket') {
          eventCommonHandler(chartEditStore.getComponentList, event.movementList, value);
          websocketEvent(event.movementList, value);
        }
      });
    });
  };
  const myWebSocket = ref();
  const lockReconnect = ref(false);
  const myWebSocketTimer = ref();

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

    tt = setTimeout(function () {
      initWebSocket();
      lockReconnect.value = false;
      // console.log("正在发起1次WebSocket重连")
    }, 120000);
  }
  function initWebSocket() {
    if ('WebSocket' in window) {
      myWebSocket.value = new WebSocket('ws://192.168.10.163:9000');
      myWebSocket.value.onopen = function () {
        console.log('websocket连接成功');
        if (myWebSocketTimer.value) {
          clearInterval(myWebSocketTimer.value);
        }
        webSocketHeart();
      };

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

  function webSocketHeart() {
    //长连接心跳检测
    let total = 1;
    myWebSocketTimer.value = setInterval(function () {
      if (myWebSocket.value) {
        // console.log("WebSocket","向服务器发送了第"+total+"条心跳检测消息");
        // myWebSocket.value.send('发送数据');
        total = total + 1;
      }
    }, 30000);
  }
  const test = () => {
    const data = {
      type: 'type1',
      data: 'test',
    };
    myWebSocket.value.send(JSON.stringify(data));
  };
  onMounted(() => {
    initWebSocket();
  });
</script>

<style lang="scss" scoped>
  @include go('preview') {
    position: relative;
    height: 100vh;
    width: 100vw;
    @include background-image('background-image');
    &.fit,
    &.full {
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      .go-preview-scale {
        transform-origin: center center;
      }
    }
    &.scrollY {
      overflow-x: hidden;
      .go-preview-scale {
        transform-origin: left top;
      }
    }
    &.scrollX {
      overflow-y: hidden;
      .go-preview-scale {
        transform-origin: left top;
      }
    }
    .go-preview-entity {
      overflow: hidden;
    }
  }
</style>
