<template>

  <div class="fatherTop">
    <el-button-group>
      <el-button :type="activeTab === 'coinConsumeDetail' ? 'primary' : 'default'"
        @click="navigateTo('coinConsumeDetail')" :disabled="!hasDetail">
        金币消耗明细
      </el-button>
      <el-button :type="activeTab === 'addCoinConsume' ? 'primary' : 'default'" @click="navigateTo('addCoinConsume')"
        :disabled="!hasAdd">
        新增消耗
      </el-button>
    </el-button-group>
  </div>
  <div class="fatherBottom">
    <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.addCoinConsume);
  hasDetail.value = hasMenuPermission(menuTree.value, permissionMapping.coinConsumeDetail);
};

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

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

// 初始化逻辑
onMounted(() => {
  initPermissions()
  if (route.name === 'coinConsume') {
    const defaultRoute = getDefaultAuditRoute();
    navigateTo(defaultRoute);
  } else {
    // 非父路由初始化当前标签状态
    if (route.name === 'addCoinConsume' || route.name === 'coinConsumeDetail') {
      activeTab.value = route.name;
    }
  }
});
</script>
<style lang="scss">
.fatherTop {
  width: 80vw;
  height: 4vh;
  float: left;
}

.fatherBottom {
  width: 80vw;
  height: 85vh;
}
</style>