<script setup lang="ts">
import { computed, onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue';
import { useAppStore } from '@/store/modules/app';
import { useRouteStore } from '@/store/modules/route';
import IframePage from '@/views/_builtin/iframe-page/[url].vue';
import { getDefaultMenu } from '@/service/api';
import HeaderBanner from './modules/header-banner.vue';
import CardData from './modules/card-data.vue';
import LineChart from './modules/line-chart.vue';
import PieChart from './modules/pie-chart.vue';
import ProjectNews from './modules/project-news.vue';
import CreativityBanner from './modules/creativity-banner.vue';

const appStore = useAppStore();
const routeStore = useRouteStore();
// 控制组件显示状态的变量
const isActive = ref(true);
const extjsContainerId = `menuRoot-${Math.random().toString(36).substr(2, 9)}`;
// 获取 MenuRoot
const menuRoot = computed(() => routeStore.menuRoot);

// 添加状态管理自动启动项
const autoStartProps = ref({
  type: '',
  kvid: '',
  url: ''
});

// 添加 extjs-root 就绪状态
const isExtjsRootReady = ref(false);

// 检查 extjs-root 是否存在
const checkExtjsRoot = () => {
  const extjsRoot = document.getElementById('extjs-root');
  isExtjsRootReady.value = Boolean(extjsRoot);
  if (!extjsRoot) {
    setTimeout(checkExtjsRoot, 100); // 继续检查
  }
};

onMounted(() => {
  checkExtjsRoot();
  isActive.value = true;
});
onActivated(() => {
  isActive.value = true;
});

onDeactivated(() => {
  isActive.value = false;
});
// 监听 MenuRoot 变化
watch(
  menuRoot,
  async newValue => {
    if (newValue) {
      const { data } = await getDefaultMenu(
        `/Restful/Kivii.Basic.Entities.Menu/Query.json?ParentKvid=${newValue.Kvid}&isRelateFunction=true`
      );

      if (data?.Results && data?.Results.length > 0) {
        const autoStartItem = data?.Results.find(item => {
          let params: { AutoStartup?: boolean | string } = {};
          try {
            if (item.Parameters) {
              params = JSON.parse(item.Parameters);
            }
            // 确保 AutoStartup 属性存在
            params.AutoStartup ||= false;
            return params.AutoStartup === true || params.AutoStartup === 'true';
          } catch (error) {
            params.AutoStartup = false;
            return false;
          }
        });

        if (autoStartItem) {
          const type = autoStartItem.Type || 'Unsupported';
          autoStartProps.value = {
            type,
            kvid: autoStartItem.Kvid || '',
            url: ''
          };
        }
      }
    }
  },
  { immediate: true }
);

const gap = computed(() => (appStore.isMobile ? 0 : 16));
</script>

<template>
  <NSpace vertical :size="16">
    <HeaderBanner />
    <NGrid :x-gap="gap" :y-gap="16" responsive="screen" item-responsive>
      <NGi span="24 s:24 m:14">
        <!-- <ProjectNews /> -->
      </NGi>
      <NGi span="24 s:24 m:10">
        <!-- <CreativityBanner /> -->
      </NGi>
    </NGrid>
    <!-- 添加 IframePage 组件，增加 isExtjsRootReady 检查 -->
    <template v-if="isExtjsRootReady">
      <div v-show="isActive" :id="extjsContainerId" style="width: 100%; height: 100%">
        <IframePage
          v-if="autoStartProps.type"
          :type="autoStartProps.type"
          :kvid="autoStartProps.kvid"
          :url="autoStartProps.url"
        />
      </div>
    </template>
  </NSpace>
</template>

<style scoped></style>
