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

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 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[]) {
      console[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);
    });
};

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

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

  console.log('Processing:', { url, kvid, type });
  const origin = window.location.origin;

  if (type === 'System') {
    console.log(url);
    if (url.startsWith('App')) {
      extTag.value = url;
    } else if (url.endsWith('.vue')) {
      // 添加.vue文件判断
      // selectTag.value = `${origin}/${url}`;
      // asyncComponent.value = `${origin}/${url}`; // 存储vue文件的URL
      loadExternalComponent(`${origin}/${url}`);
    } else {
      selectTag.value = `${origin}/${url}`;
    }
    console.log('url1:', url);
    console.log('kvid1:', kvid);
    console.log('type1:', type);
  } else {
    console.log('url2:', url);
    console.log('kvid2:', kvid);
    console.log('type2:', type);
    try {
      const { data: selectMenu } = await getSelectMenu(
        `/Restful/Kivii.Basic.Entities.Function/Access.json?MenuKvids=${kvid}`
      );

      if (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结尾
            // asyncComponent.value = `${origin}${handler}`;
            loadExternalComponent(`${origin}${handler}`);
          } else {
            // 如果不以.vue结尾
            selectTag.value = `${origin}${handler}`;
          }
        } else {
          extTag.value = handler;
        }
      } else {
        hasError.value = true;
      }
    } catch (error) {
      console.error('Menu access error:', error);
      hasError.value = true;
    }
  }
};

// 监听 props 变化
watch(
  [() => type, () => kvid, () => url],
  () => {
    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"
      class="size-full"
      :url="selectTag"
    ></WebviewComponent>
    <ExtJsComponent v-else-if="extTag && !hasError" :key="extTag" :url="extTag"></ExtJsComponent>
    <VueComponent v-else-if="asyncComponent && !hasError" :url="asyncComponent"></VueComponent>
    <NotFound v-else />
  </div>
</template>

<style scoped></style>
