<template>
  <div>
    <el-button-group>
      <el-button
          :type="activeTab === 'addBeanRecharge' ? 'primary' : 'default'"
          @click="navigateTo('addBeanRecharge')"
          :disabled="!hasAdd"
          style="width: 120px;"
      >
        新增充值
      </el-button>
      <el-button
          :type="activeTab === 'beanSystemRecharge' ? 'primary' : 'default'"
          @click="navigateTo('beanSystemRecharge')"
          :disabled="!hasSystem"
          style="width: 120px;"
      >
        系统充值
      </el-button>
      <el-button
          :type="activeTab === 'beanOnlineRecharge' ? 'primary' : 'default'"
          @click="navigateTo('beanOnlineRecharge')"
          :disabled="!hasOnline"
          style="width: 120px;"
      >
        线上充值
      </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';
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 hasSystem = ref(false);
const hasOnline = 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_Golden_Bean_Recharge);
  hasSystem.value = hasMenuPermission(menuTree.value, permissionMapping.View_Golden_Bean_System_Recharge_Details);
  hasOnline.value = hasMenuPermission(menuTree.value, permissionMapping.View_Golden_Bean_Online_Recharge_Details);
};

// 默认跳转逻辑
const getDefaultAuditRoute = () => {
  initPermissions();
  if (hasAdd.value) return 'addBeanRecharge';
  if (hasSystem.value) return 'beanSystemRecharge';
  if (hasOnline.value) return 'beanOnlineRecharge';
  return 'addBeanRecharge';
};

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

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