<template>
  <div style="height:4vh;">
    <el-button-group>
      <el-button :type="activeTab === 'addCoinRecharge' ? 'primary' : 'default'" @click="navigateTo('addCoinRecharge')"
        :disabled="!hasAdd">
        新增充值
      </el-button>
      <el-button :type="activeTab === 'coinRechargeDetail' ? 'primary' : 'default'"
        @click="navigateTo('coinRechargeDetail')" :disabled="!hasDetail">
        金币充值明细
      </el-button>
    </el-button-group>
  </div>
    <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 hasAdd = ref(false);
const hasDetail = ref(false);
// 导航方法
const navigateTo = (name) => {
  activeTab.value = name;
  router.push({ name });
};


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

  hasAdd.value = hasMenuPermission(menuTree.value, permissionMapping.Submit_Gold_Coin_Recharge);
  hasDetail.value = hasMenuPermission(menuTree.value, permissionMapping.View_Gold_Coin_Recharge_Details);
};

// 默认跳转逻辑
const getDefaultAuditRoute = () => {
  initPermissions();
  if (hasAdd.value) return 'addCoinRecharge';
  if (hasDetail.value) return 'coinRechargeDetail';
  return 'addCoinRecharge';
};

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

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