<template>
  <div>
    <!-- 这里放置标签切换的按钮 -->
    <el-button-group>
      <!-- 切换后状态显示 primary 样式否则是默认样式 -->
      <el-button
          :type="activeTab === 'detail' ? 'primary' : 'default'"
          @click="goToAdd"
      >
        金币明细
      </el-button>
      <el-button
          :type="activeTab === 'balance' ? 'primary' : 'default'"
          @click="goToDetail"
      >
        金币余额
      </el-button>
    </el-button-group>
    <!-- 渲染子路由组件 -->
    <router-view></router-view>
  </div>
</template>

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

const adminStore = useAdminStore();
const {menuTree} = storeToRefs(adminStore);

const router = useRouter();// 获取路由实例
const route = useRoute();// 获取当前路由信息
// 定义响应式变量 activeTab 来跟踪当前激活的标签
const activeTab = ref(route.name === 'clientCountBalance' ? 'balance' : 'detail');


const goToAdd = () => {
  // 点击按钮时更新 activeTab 为 add
  activeTab.value = 'detail';
  router.push({ name: 'clientCountDetail' });
};

const goToDetail = () => {
  // 点击按钮时更新 activeTab 为 detail
  activeTab.value = 'balance';
  router.push({ name: 'clientCountBalance' });
};

// 导航方法
const navigateTo = (name) => {
  activeTab.value = name;
  if (name === 'detail') {
    router.push({name: 'clientCountDetail'});
  } else if (name === 'balance') {
    router.push({name: 'clientCountBalance'});
  }
};


// 递归判断某个 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 getDefaultRoute = () => {
  if (!menuTree.value) return 'detail';
  const hasRecharge = hasMenuPermission(menuTree.value, '查看金币明细');
  return hasRecharge ? 'detail' : 'balance';
};


// 监听路由变化更新标签状态
watch(() => route.name, (newName) => {
  if (newName === 'detail' || newName === 'balance') {
    activeTab.value = newName;
  } else if (newName === 'usergold') {
    const defaultRoute = getDefaultRoute();
    navigateTo(defaultRoute);
  }
});

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