<template>
  <div class="plan">
    <!-- src=" http://192.168.1.128:3001/zutai/?id=44368e72a2e594d14ebaf317f0f6ad00&&name=decodeURI(APP测试项目)&&flag=true&&wxqr=true#/" -->
    <!-- <iframe
      src="http://192.168.1.62:8088/zutai/?id=0944fe372e90daeefd040916a105ac8b&&name=测试组态编辑器&&preview=true#/preview"
      width="100%"
      height="100%"
      frameborder="0"
    ></iframe> -->
    <!-- 添加加载事件监听 -->
    <iframe
      :src="iframeSrc"
      width="100%"
      height="100%"
      frameborder="0"
      scrolling="no"
      id="iframeLeft"
      @load="onIframeLoad"
    ></iframe>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import { getActive } from "@/api/manage_wx/index";

const props = defineProps<{
  project: { id: string; name: string } | null;
}>();

const iframeSrc = ref("");

// 监听 props 变化
watch(
  () => props.project,
  (newVal) => {
    if (newVal && newVal.id && newVal.name) {
      //   window.location.origin
      iframeSrc.value =
        window.location.origin +
        `/zutai/?id=${newVal.id}&&name=${encodeURIComponent(
          newVal.name
        )}&&preview=true&&display=true&&graphicDisplay=wx#/preview`;

      // console.log("更新 iframeSrc:", iframeSrc.value);
    }
  },
  { immediate: true, deep: true }
);

onMounted(() => {
  // 监听来自 eventStatistics 组件的消息
  window.addEventListener("message", handleMessage);

  getActive({}).then((res: any) => {
    if (res.code == "A0000") {
      //   window.location.origin
      iframeSrc.value =
        window.location.origin +
        `/zutai/?id=${res.data.id}&&name=${encodeURIComponent(
          res.data.name
        )}&&preview=true&&display=true&&graphicDisplay=wx#/preview`;
    }
  });
});

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener("message", handleMessage);
});

// iframe 加载完成回调  添加加载事件监听
const onIframeLoad = () => {
  // console.log("iframe 加载完成");
  // 通知 securityDetail.vue 组件 iframe 已加载完成
  window.postMessage(
    {
      type: "IFRAME_LOADED",
      data: { loaded: true },
    },
    "*"
  );
};

// 处理来自 eventStatistics 组件的消息
const handleMessage = (event: MessageEvent) => {
  // 验证消息来源（在生产环境中应该验证 origin）
  // if (event.origin !== 'trusted-origin') return;

  const { type, payload } = event.data;

  if (type === "SEND_KEYS_TO_IFRAME") {
    // 将数据转发给 iframe
    sendKeysToIframe(payload);
  }
};

// 向 iframe 发送 keyList 数据
const sendKeysToIframe = (keyList: string[]) => {
  const iframe = document.getElementById("iframeLeft") as HTMLIFrameElement;
  if (iframe && iframe.contentWindow) {
    iframe.contentWindow.postMessage(
      {
        type: "ANALYSIS_KEYS",
        payload: keyList,
      },
      "*"
    ); // 在生产环境中应该指定具体的域名而不是 '*'
  }
};

</script>
<style lang="scss" scoped>
.plan {
  width: 100%;
  height: 990px;
  padding: 5px;
}
</style>
