<template>
  <div>
    <div style="height:4vh;width:82vw;">
    <el-button-group>
      <el-button :type="activeTab === 'rechargeAudit' ? 'primary' : 'default'" @click="navigateTo('rechargeAudit')"
        :disabled="!hasRecharge">
        充值审核
      </el-button>
      <el-button :type="activeTab === 'refundAudit' ? 'primary' : 'default'" @click="navigateTo('refundAudit')"
        :disabled="!hasRefund">
        退款审核
      </el-button>
    </el-button-group>
    </div>
    <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";
import { ElMessage } from 'element-plus';

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

const activeTab = ref('');
const hasRecharge = ref(false);
const hasRefund = ref(false);
// 导航方法
const navigateTo = (name) => {
  if(name == 'rechargeAudit'){
    if(!hasRecharge){
      ElMessage.error('您暂无充值审核操作权限')
      return;
    }
  }else if(name = 'refundAudit'){
   if(!hasRefund){
      ElMessage.error('您暂无退款审核操作权限')
      return;
    } 
  }
  activeTab.value = name;
  router.push({ name });
};


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

  hasRecharge.value = hasMenuPermission(menuTree.value, permissionMapping.rechargeAudit);
  hasRefund.value = hasMenuPermission(menuTree.value, permissionMapping.refundAudit);
};

// 默认跳转逻辑
const getDefaultAuditRoute = () => {
  initPermissions();
  if (hasRecharge.value) return 'rechargeAudit';
  if (hasRefund.value) return 'refundAudit';
  return 'rechargeAudit';
};

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

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