<template>
  <div>
    <el-button-group>
      <el-button
          :type="activeTab === 'rechargeAudit' ? 'primary' : 'default'"
          @click="navigateTo('rechargeAudit')"
      >
        充值审核
      </el-button>
      <el-button
          :type="activeTab === 'refundAudit' ? 'primary' : 'default'"
          @click="navigateTo('refundAudit')"
      >
        退款审核
      </el-button>
    </el-button-group>
    <router-view></router-view>
  </div>
</template>

<script setup>
import {ref, watch, onMounted} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {storeToRefs} from 'pinia';
import {useAdminStore} from '@/store/index.js';

const router = useRouter();
const route = useRoute();
const adminStore = useAdminStore();
const {menuTree} = storeToRefs(adminStore);

const activeTab = ref('');

// 导航方法
const navigateTo = (name) => {
  activeTab.value = name;
  router.push({name});
};

// 递归判断某个 menuName 是否存在
const hasMenuPermission = (tree, targetName) => {
  for (const node of tree) {
    if (node.menuName === targetName) return true;
    if (node.children && hasMenuPermission(node.children, targetName)) return true;
  }
  return false;
};

// 默认路由判断
const getDefaultAuditRoute = () => {
  if (!menuTree.value) return 'rechargeAudit';

  const hasRecharge = hasMenuPermission(menuTree.value, '充值审核');
  return hasRecharge ? 'rechargeAudit' : 'refundAudit';
};
// 监听路由变化更新标签状态
watch(() => route.name, (newName) => {
  if (newName === 'rechargeAudit' || newName === 'refundAudit') {
    activeTab.value = newName;
  } else if (newName === 'audit') {
    // 每次访问 /audit 都进行默认跳转
    const defaultRoute = getDefaultAuditRoute();
    navigateTo(defaultRoute);
  }
});


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