<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 hasUser = ref(false);
const hasRole = ref(false);
// 导航方法
const navigateTo = (name) => {
  activeTab.value = name;
  router.push({ name });
};


// 初始化权限状态
const initPermissions = () => {
  if (!menuTree.value || !menuTree.value.length) return;

  hasUser.value = hasMenuPermission(menuTree.value, permissionMapping.user_management);
  hasRole.value = hasMenuPermission(menuTree.value, permissionMapping.role_management);
  console.log('====================================', hasUser.value, hasRole.value)
};

// 默认跳转逻辑
const getDefaultAuditRoute = () => {
  initPermissions();
  if (hasUser.value) return 'userPermission';
  if (hasRole.value) return 'rolePermission';
  return 'userPermission';
};

// 监听路由变化更新标签状态
watch(() => route.name, (newName) => {
  initPermissions()
  if (newName === 'userPermission' || newName === 'rolePermission') {
    activeTab.value = newName;
  } else if (newName === 'permissions') {
    // 每次访问 /permissions 都进行默认跳转
    const defaultRoute = getDefaultAuditRoute();
    navigateTo(defaultRoute);
  }
});

// 初始化逻辑
onMounted(() => {
  initPermissions()
  if (route.name === 'permissions') {
    const defaultRoute = getDefaultAuditRoute();
    navigateTo(defaultRoute);
  } else {
    // 非父路由初始化当前标签状态
    if (route.name === 'userPermission' || route.name === 'rolePermission') {
      activeTab.value = route.name;
    }
  }
});
</script>