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

import { getVisual2DMsgType, Visual2DMsgType, visual2DPreviewPageUrl } from '.';

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

interface Props {
  info: GroupModuleInfo;
  deviceList?: DeviceGroupTree[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  click: [];
  openDevCtrlModal: [id: number, valveType: number];
}>();

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

const iframeUrl = computed(() => {
  const { leId, moduleType } = props.info;

  return `${visual2DPreviewPageUrl}?${qs.stringify({
    id: leId,
    moduleType,
  })}`;
});

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

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

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

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

  if (msgType === getVisual2DMsgType(Visual2DMsgType.PreviewLoaded)) {
    isIframeLoaded.value = true;
    sendDeviceData();
  } else if (msgType === getVisual2DMsgType(Visual2DMsgType.PreviewClicked)) {
    emit('click');
  } else if (msgType === getVisual2DMsgType(Visual2DMsgType.OpenDevCtrlModal)) {
    emit('openDevCtrlModal', e.data.hvacDeviceId, e.data.hvacValveType);
  }
};

const sendDeviceData = () => {
  if (props.deviceList) {
    const msg: IframeMsg = {
      msgType: getVisual2DMsgType(Visual2DMsgType.SendDeviceData),
      deviceList: JSON.parse(JSON.stringify(props.deviceList)),
    };

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

const exportImg = () => {
  const msg: IframeMsg = {
    msgType: getVisual2DMsgType(Visual2DMsgType.ExportImg),
    imgName: '2D组态',
  };

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

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

<template>
  <iframe class="visual-2d-preview" ref="previewIframe" :src="iframeUrl"></iframe>
  <ASpin v-if="!isIframeLoaded" class="center-loading visual-2d-preview-loading" :spinning="true" />
</template>

<style lang="scss" scoped>
.visual-2d-preview {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: transparent;
  border: none;
  border-radius: inherit;
}

.visual-2d-preview-loading {
  background-color: inherit;
  border-radius: inherit;
}
</style>
