<script setup lang="ts">
import { onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue';

import { EnvAreaMsgType, envAreaPreviewPageUrl, getEnvAreaMsgType } from '@/utils/env-area';

import type { IframeMsg, RegionsPointsItem } from '@/types';

interface Props {
  areaData?: RegionsPointsItem;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  highlightEnvPoint: [id: number];
}>();

const iframeRef = useTemplateRef('previewIframe');
const isIframeLoaded = ref(false);

onMounted(() => {
  window.addEventListener('message', handleIframeMsg);
});

onUnmounted(() => {
  window.removeEventListener('message', handleIframeMsg);
});

watch(
  () => props.areaData,
  () => {
    if (isIframeLoaded.value) {
      sendAreaData();
    }
  },
  { deep: true },
);

const handleIframeMsg = (e: MessageEvent<IframeMsg>) => {
  const { msgType } = e.data;

  if (msgType === getEnvAreaMsgType(EnvAreaMsgType.PreviewLoaded)) {
    isIframeLoaded.value = true;
    sendAreaData();
  } else if (msgType === getEnvAreaMsgType(EnvAreaMsgType.HighlightEnvMonitorPoint)) {
    emit('highlightEnvPoint', e.data.monitorPointId);
  }
};

const sendAreaData = () => {
  if (props.areaData) {
    const msg: IframeMsg = {
      msgType: getEnvAreaMsgType(EnvAreaMsgType.PreviewArea),
      ...JSON.parse(JSON.stringify(props.areaData)),
    };

    iframeRef.value?.contentWindow?.postMessage(msg, '*');
  }
};

const highlightCanvasPoint = (id: number) => {
  const msg: IframeMsg = {
    msgType: getEnvAreaMsgType(EnvAreaMsgType.HighlightCanvasMonitorPoint),
    monitorPointId: id,
  };

  iframeRef.value?.contentWindow?.postMessage(msg, '*');
};

defineExpose({
  highlightCanvasPoint,
});
</script>

<template>
  <iframe class="env-area-preview" ref="previewIframe" :src="envAreaPreviewPageUrl"></iframe>
  <ASpin v-if="!isIframeLoaded" class="center-loading env-area-preview-loading" :spinning="true" />
</template>

<style lang="scss" scoped>
.env-area-preview {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: transparent;
  border: none;
  border-radius: 12px;
}

.env-area-preview-loading {
  background-color: inherit;
  border-radius: inherit;
}
</style>
