<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const host = window.location.origin;
const path = import.meta.env.VITE_APP_AIAGENTURL + '?';
const param = `token=${encodeURIComponent(localStorage.getItem('plantToken') as string)}&source=app`;
const url = host + path + param;
const iframe = ref<HTMLIFrameElement | null>(null);
const router = useRouter();
onMounted(() => {
  // 保存原始的window.open方法
  const originalOpen = window.open;

  // 监听iframe的load事件，确保iframe已完全加载
  iframe.value?.addEventListener('load', () => {
    try {
      const iframeWindow = iframe.value?.contentWindow;

      // 尝试覆盖iframe的open方法
      if (iframeWindow) {
        // 方法一：直接覆盖
        try {
          iframeWindow.open = function (...args: any[]) {
            const url = new URL(args[0]); // 使用 URL API 解析
            const path = url.pathname; // 获取路径部分
            const query = Object.fromEntries(url.searchParams); // 将 search 转换为对象
            // 如果需要去除特定 host 前缀（如本地调试）
            if (url.host === window.location.host) {
              args[0] = args[0].replace(`https://${url.host}`, '');
            }
            router.push({
              path,
              query
            });
          };
        } catch (e) {
          // 方法二：如果直接覆盖失败，尝试使用defineProperty
          try {
            Object.defineProperty(iframeWindow, 'open', {
              value: function (...args: any[]) {
                // console.log('iframe中的open方法被调用，参数：', args);
                return originalOpen.apply(window, args as any);
              },
              writable: true,
              configurable: true
            });
          } catch (e2) {
            console.error('无法覆盖iframe的open方法(defineProperty)：', e2);
          }
        }
      }
    } catch (error) {
      console.error('无法覆盖iframe的open方法：', error);
    }
  });
});
</script>

<template>
  <iframe ref="iframe" style="height: 100%; width: 100%" :src="url" frameborder="0"></iframe>
</template>

<style scoped lang="scss"></style>
