<template>
  <div>
    <!-- 这里放置标签切换的按钮 -->
    <el-button-group>
      <!-- 切换后状态显示 primary 样式否则是默认样式 -->
      <el-button
          :type="activeTab === 'add' ? 'primary' : 'default'"
          @click="goToAdd"
      >
        新增退款
      </el-button>
      <el-button
          :type="activeTab === 'detail' ? '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 === 'coinRefundDetail' ? 'detail' : 'add');


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

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

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


// 递归判断某个 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 'add';
  const hasRecharge = hasMenuPermission(menuTree.value, '提交金币退款');
  return hasRecharge ? 'add' : 'detail';
};


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

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