<script setup lang="ts">
import RightTabs from '@/components/RightTabs/RightTabs.vue';
import { getStoreData } from '@/utils/composition';
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted, watch, computed } from 'vue';
import type { ISystemRightTabList } from '@/model/nav-datatype';
import { getValidSystemIds, getCurrentSystemId, isMultiHostEnvironment, validateSystemIds } from '@/utils/system-ids';

const router = useRouter();
const route = useRoute();

// 获取架构支持信息
const armSupport = computed(() => getStoreData('loct', 'armspt'));
const cpuSupport = computed(() => getStoreData('loct', 'cpuspt'));

interface BiosTabItem extends ISystemRightTabList {
  id: string;
  name: string;
}

const baseTabList: BiosTabItem[] = [
  {
    id: 'biosTab',
    index: '0',
    label: 'BIOS_BOOT_DEVICE',
    name: 'bios',
    router: '/navigate/system/bios-settings/bios',
  },
  {
    id: 'cpuTab',
    index: '1',
    label: 'BIOS_CPU_ADJUSTMENT',
    name: 'cpu',
    router: '/navigate/system/bios-settings/cpu',
  },
  {
    id: 'biosSettingTab',
    index: '2',
    label: 'BIOS_CONFIG_MENU',
    name: 'setting',
    router: '/navigate/system/bios-settings/setting',
  },
  {
    id: 'biosConfigExportTab',
    index: '3',
    label: 'BIOS_CONFIG_EXPORT',
    name: 'export',
    router: '/navigate/system/bios-settings/export',
  },
];

const tabList = computed(() => {
  // Arm架构不支持CPU操作，不显示CPU页面
  if (armSupport.value || !cpuSupport.value) {
    return baseTabList.filter(item => item.name !== 'cpu');
  }
  return baseTabList;
});

/**
 * 计算当前路由对应的Tab索引
 * 
 * 通过匹配当前路由路径与tabList中的router字段来确定当前应选中的Tab
 * 如果未找到匹配项，默认返回第一个Tab（'0'）
 */
const getCurrentTabIndex = (): string => {
  const currentPath = route.fullPath;
  const currentTab = tabList.value.find(item => currentPath.includes(item.router));
  return currentTab ? currentTab.index : '0';
};

const currentIdx = ref(getCurrentTabIndex());

// 监听路由路径变化，更新选中的Tab
watch(
  () => route.path,
  () => {
    currentIdx.value = getCurrentTabIndex();
  },
);

const handleSelect = (key: string) => {
  const targetTab = tabList.value.find(item => item.index === key);
  if (targetTab) {
    // 保留当前的主机参数（如果存在）
    const currentQuery = { ...route.query };
    router.push({
      path: targetTab.router,
      query: currentQuery,
    });
  }
};

// 多主机相关变量
const isMultiHost = ref(false);
const currentHost = ref('1');
const systemIds = ref<number[]>([]);

interface MultiHostTabItem extends ISystemRightTabList {
  id: string;
  index: string;
  router: string;  // 路由参数字符串，如'systemId=1'
}

const multiHostTabs = ref<MultiHostTabItem[]>([
  {
    id: 'host1',
    label: 'HOME_HOST_0',
    index: '1',
    router: 'systemId=1',
  },
  {
    id: 'host2',
    label: 'HOME_HOST_1',
    index: '2',
    router: 'systemId=2',
  },
]);

// 根据SystemIds数据初始化Bios相关状态
const initBiosConfig = async () => {
  // 获取SystemIds数据（不需要验证，路由守卫已经保证正确性）
  systemIds.value = await getValidSystemIds();

  // 直接使用当前路由参数（路由守卫已经修正过）
  isMultiHost.value = isMultiHostEnvironment(systemIds.value);
  currentHost.value = getCurrentSystemId(route.query, systemIds.value);

  // 更新主机Tab配置
  if (systemIds.value.length === 2) {
    multiHostTabs.value = systemIds.value.map(id => ({
      id: `host${id}`,
      label: id === 1 ? 'HOME_HOST_0' : 'HOME_HOST_1',
      index: String(id),
      router: `systemId=${id}`,
    }));
  }
};

const handleSelectHost = (value: string) => {
  // 更新当前主机
  currentHost.value = value;
  // 更新路由参数，保持其他查询参数不变
  router.push({
    ...route,
    query: { ...route.query, systemId: value },
  });
};

/**
 * 监听路由参数变化，处理手动修改URL的情况
 */
watch(
  () => route.query.systemId,
  async (newVal, oldVal) => {
    if (newVal === oldVal) {
      return;
    }

    try {
      const validationResult = await validateSystemIds(route);

      // 检查是否需要修正查询参数
      const hasQueryChanged = JSON.stringify(validationResult.validatedQuery) !== JSON.stringify(route.query);

      if (hasQueryChanged) {
        // 需要修正路由参数，进行重定向
        router.replace({
          ...route,
          query: validationResult.validatedQuery,
        });
      } else {
        // 参数有效，更新当前主机显示
        if (validationResult.currentSystemId) {
          currentHost.value = validationResult.currentSystemId;
        }
      }
    } catch (error) {
      // 验证失败，修正路由参数
      router.replace({...route, query: {} });
    }
  },
);

/**
 * 组件挂载生命周期钩子
 * 
 * 主要任务：
 * 1. 获取有效的SystemIds数据
 * 2. 初始化多主机环境配置
 */
onMounted(() => {
  initBiosConfig();
});
</script>

<template>
  <div class="root-container">
    <div class="bios-config">
      <template v-if="isMultiHost">
        <!-- 主机选择器 - 使用RightTabs组件实现主机切换 -->
        <RightTabs
          :check-tab-index="currentHost"
          :tab-list="multiHostTabs"
          :is-route-mode="false"
          @handle-select="handleSelectHost"
        />
        <el-tabs v-model="currentIdx" class="multi-host-bios-tabs" @tab-change="handleSelect">
          <el-tab-pane v-for="item in tabList" :key="item.name" :label="$t(item.label)" :name="item.index" />
        </el-tabs>
      </template>
      <RightTabs
        v-else
        :check-tab-index="currentIdx"
        :tab-list="tabList"
        :is-route-mode="true"
        @handle-select="handleSelect"
      />
      <router-view @handle-change="handleSelect" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 多主机环境下BIOS Tab的自定义样式
.multi-host-bios-tabs {
  background: #fff;
  padding: 16px 24px 0;
  margin-right: 24px;

  :deep(.el-tabs__nav-wrap) {
    transform: translateZ(0);
  }

  :deep(.el-tabs__item) {
    line-height: 32px;
    padding-top: 0;
    padding-bottom: 0;
    font-weight: 600;
  }
}
</style>