<!-- eslint-disable no-console -->
<!-- eslint-disable @typescript-eslint/no-shadow -->
<script setup lang="ts">
import { nextTick, onActivated, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { useEventBus } from '@vueuse/core'; // 添加事件总线
import { loadModule } from 'vue3-sfc-loader';
import { getSelectMenu } from '@/service/api';
import NotFound from '@/views/_builtin/404/index.vue'; // 引入 404 组件
import { useTabStore } from '@/store/modules/tab';
import ExtJsComponent from './extJs.vue';
import WebviewComponent from './webview.vue';
import VueComponent from './vueComponent.vue'; // 添加新组件导入

// 添加组件选项
defineOptions({ name: 'IframePage' });

interface Props {
  url: string;
  kvid: string;
  type: string;
}
// 定义响应式变量
const asyncComponent = shallowRef<any>(null);
const { url, kvid, type } = defineProps<Props>();
const selectTag = ref('');
const extTag = ref('');
const hasError = ref(false);

// 组件引用
const webviewRef = ref<any>(null);
const extJsRef = ref<any>(null);
const vueComponentRef = ref<any>(null);

// 监听标签关闭事件
const tabCloseEventBus = useEventBus<string>('tab-close');

const tabStore = useTabStore();

// 清理所有资源的函数
const cleanupResources = () => {
  // console.log('清理iframe-page资源');

  // 清理webview (iframe)
  if (webviewRef.value && typeof webviewRef.value.cleanup === 'function') {
    webviewRef.value.cleanup();
  }

  // 清理ExtJS组件
  if (extJsRef.value && typeof extJsRef.value.cleanup === 'function') {
    extJsRef.value.cleanup();
  }

  // 清理Vue组件
  if (vueComponentRef.value && typeof vueComponentRef.value.cleanup === 'function') {
    vueComponentRef.value.cleanup();
  }

  // 重置状态
  asyncComponent.value = null;
  selectTag.value = '';
  extTag.value = '';
  hasError.value = false;
};

// 监听标签关闭事件
tabCloseEventBus.on(closedTabId => {
  // 只有当关闭的是当前标签时才清理资源
  if (closedTabId === tabStore.activeTabId) {
    cleanupResources();
  }
});

// 组件卸载前清理
onBeforeUnmount(() => {
  cleanupResources();
  // 移除事件监听
  tabCloseEventBus.off();
});

// 修复console[type]的类型错误
const safeConsoleLog = (type: string, ...args: any[]) => {
  if (type === 'error') {
    console.error(...args);
  } else if (type === 'warn') {
    console.warn(...args);
  } else if (type === 'info') {
    console.info(...args);
  } else {
    console.log(...args);
  }
};

// 定义加载外部组件的函数
const loadExternalComponent = async (url: string) => {
  const options = {
    moduleCache: {
      vue: await import('vue')
    },
    // eslint-disable-next-line @typescript-eslint/no-shadow
    async getFile(url: string) {
      const res = await fetch(url);
      if (!res.ok) {
        throw new Error(`Failed to fetch ${url}`);
      }
      return await res.text();
    },
    addStyle(textContent: string) {
      const style = document.createElement('style');
      style.textContent = textContent;
      document.head.appendChild(style);
    },
    log(type: string, ...args: any[]) {
      safeConsoleLog(type, ...args);
    }
  };

  // 使用 loadModule 加载外部组件
  loadModule(url, options)
    .then(component => {
      asyncComponent.value = component;
      // console.log('Component loaded:', asyncComponent.value);
    })
    .catch(error => {
      console.error('Error loading component:', error);
      hasError.value = true;
    });
};

// 将处理逻辑抽取为函数
const handleMenuAccess = async () => {
  if (!type || !kvid) return;

  // 确保 DOM 已准备好
  await nextTick();

  // console.log('Processing:', { url, kvid, type });
  const origin = window.location.origin;
  // 创建后端地址 - 假设后端在80端口
  const backendOrigin = origin.replace(':8080', ':80');

  if (type === 'System') {
    console.log(url);
    if (url.startsWith('App')) {
      extTag.value = url;
    } else if (url.endsWith('.vue')) {
      // 使用后端地址加载Vue文件
      loadExternalComponent(`${backendOrigin}/${url}`);
    } else {
      selectTag.value = `${backendOrigin}/${url}`;
    }
  } else {
    try {
      const { data: selectMenu } = await getSelectMenu(
        `/Restful/Kivii.Basic.Entities.Function/Access.json?MenuKvids=${kvid}`
      );

      // 修复类型错误
      if (selectMenu?.Results && selectMenu.Results.length > 0) {
        const handler = selectMenu.Results[0].Handler;
        // 确保在设置 extTag 之前 DOM 已准备好
        if (!handler.startsWith('/') && !handler.endsWith('.vue')) {
          await nextTick();
          extTag.value = handler;
        } else if (handler.slice(0, 1) === '/') {
          // 先判断是否以/开头
          if (handler.endsWith('.vue')) {
            // 如果以.vue结尾
            loadExternalComponent(`${backendOrigin}${handler}`);
          } else {
            // 如果不以.vue结尾
            selectTag.value = `${backendOrigin}${handler}`;
          }
        } else {
          extTag.value = handler;
        }
      } else {
        // hasError.value = true;
        selectTag.value = `${url}`;
        console.log(selectTag.value);
      }
    } catch (error) {
      console.error('Menu access error:', error);
      hasError.value = true;
    }
  }
};

// 监听 props 变化
watch(
  [() => type, () => kvid, () => url],
  () => {
    // 先清理旧资源
    cleanupResources();
    // 然后加载新内容
    handleMenuAccess();
  },
  { immediate: true }
);

// onActivated 时也执行
onActivated(() => {
  handleMenuAccess();
});

onMounted(() => {
  // console.log('mounted');
  const origin = window.location.origin;
  origin.split('/').slice(0, 3).join('/');
  // loadExternalComponent(`${origin}/codet/testComponent.vue`);
  // loadExternalComponent(`localhost:8081//src/views/_builtin/iframe-page/extJs.vue`);
});
</script>

<template>
  <div class="h-full">
    <WebviewComponent
      v-if="selectTag && !hasError && !asyncComponent"
      id="iframePage"
      ref="webviewRef"
      class="size-full"
      :url="selectTag"
    ></WebviewComponent>
    <ExtJsComponent v-else-if="extTag && !hasError" ref="extJsRef" :key="extTag" :url="extTag"></ExtJsComponent>
    <VueComponent v-else-if="asyncComponent && !hasError" ref="vueComponentRef" :url="asyncComponent"></VueComponent>
    <NotFound v-else />
  </div>
</template>

<style scoped></style>
