<template>
      <router-view></router-view>
  </template>
  
  <script setup>
  import {onMounted, ref, watch} from 'vue';
  import {useRoute, useRouter} from 'vue-router';
  import {storeToRefs} from "pinia";
  import {useAdminStore} from "@/store/index.js";
  import {hasMenuPermission, permissionMapping} from "@/utils/menuTreePermission.js";
  
  const router = useRouter();
  const route = useRoute();
  const adminStore = useAdminStore();
  const {menuTree} = storeToRefs(adminStore);
  
  const activeTab = ref('');
  const hasNew = ref(false);
  const hasOld = ref(false);
  // 导航方法
  const navigateTo = (name) => {
    activeTab.value = name;
    router.push({name});
  };
  
  
  // 初始化权限状态
  const initPermissions = () => {
    if (!menuTree.value || !menuTree.value.length) return
  
    hasNew.value = hasMenuPermission(menuTree.value, permissionMapping.newCoinSelect)
    hasOld.value = hasMenuPermission(menuTree.value, permissionMapping.oldCoinSelect)
  }
  
  // 默认跳转逻辑
  const getDefaultAuditRoute = () => {
    initPermissions()
    if (hasNew.value) return 'newHistory'
    if (hasOld.value) return 'oldHistory'
    return 'newHistory'
  };
  
  // 监听路由变化更新标签状态
  watch(() => route.name, (newName) => {
    initPermissions()
    if (newName === 'newHistory' || newName === 'oldHistory') {
      activeTab.value = newName;
    } else if (newName === 'history') {
      // 每次访问 /history 都进行默认跳转
      const defaultRoute = getDefaultAuditRoute();
      navigateTo(defaultRoute);
    }
  });
  
  // 初始化逻辑
  onMounted(() => {
    initPermissions()
    console.log('============================',hasNew.value,hasOld.value)
    if (route.name === 'history') {
      const defaultRoute = getDefaultAuditRoute();
      navigateTo(defaultRoute);
    } else {
      // 非父路由初始化当前标签状态
      if (route.name === 'newHistory' || route.name === 'oldHistory') {
        activeTab.value = route.name;
      }
    }
  });
  </script>
  <style>
  </style>