<template>
  <div class="father">
    <!-- 这里放置标签切换的按钮 -->
    <el-button-group>
            <el-button :type="activeTab === 'coinRefundDetail' ? 'primary' : 'default'"
                 @click="navigateTo('coinRefundDetail')" :disabled="!hasDetail" v-if="hasDetail">
        金币退款明细
      </el-button>
      <!-- 切换后状态显示 primary 样式否则是默认样式 -->
      <el-button :type="activeTab === 'addCoinRefund' ? 'primary' : 'default'" @click="navigateTo('addCoinRefund')"
                 :disabled="!hasAdd" v-if="hasAdd">
        新增退款
      </el-button>
    </el-button-group>
    <!-- 渲染子路由组件 -->
  </div>
  <div>
    <router-view></router-view>
  </div>
</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.addCoinRefund);
  hasDetail.value = hasMenuPermission(menuTree.value, permissionMapping.coinRefundDetail);
};

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

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

// 初始化逻辑
onMounted(() => {
  initPermissions()
  if (route.name === 'coinRefund') {
    const defaultRoute = getDefaultAuditRoute();
    navigateTo(defaultRoute);
  } else {
    // 非父路由初始化当前标签状态
    if (route.name === 'coinRefundDetail' || route.name === 'addCoinRefund') {
      activeTab.value = route.name;
    }
  }
});
</script>
<style lang="css">
.father {
  width: 82vw;
  height: 4vh;
}
</style>