<script setup lang="ts">
import { ArrowRight, Fold, SwitchButton } from '@element-plus/icons-vue';
import { computed, ref } from 'vue';
import { RouterView, useRoute, useRouter } from 'vue-router';
import { routes } from './router';
import { useAuthStore } from './stores/auth';

const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const collapsed = ref(false);

const publicPage = computed(() => Boolean(route.meta.public));
const menuRoutes = computed(() =>
  routes.filter((item) => !item.meta?.public && !item.meta?.hidden && auth.hasRole(item.meta?.authority as string[] | undefined)),
);

async function logout() {
  await auth.logout();
  router.push('/auth/login');
}
</script>

<template>
  <RouterView v-if="publicPage" />
  <div v-else class="admin-shell">
    <aside class="side-rail" :class="{ collapsed }">
      <div class="brand-mark">
        <div class="brand-sigil">D</div>
        <div class="brand-copy">
          <b>Dramix</b>
          <span>Operations</span>
        </div>
      </div>
      <el-menu :default-active="route.path" router class="nav-menu" :collapse="collapsed">
        <el-menu-item v-for="item in menuRoutes" :key="item.path" :index="item.path">
          <el-icon><component :is="item.meta?.icon" /></el-icon>
          <span>{{ item.meta?.title }}</span>
        </el-menu-item>
      </el-menu>
    </aside>
    <main class="workbench">
      <header class="topbar">
        <div class="crumb">
          <el-button :icon="Fold" circle text @click="collapsed = !collapsed" />
          <span>运营后台</span>
          <el-icon><ArrowRight /></el-icon>
          <strong>{{ route.meta.title }}</strong>
        </div>
        <div class="operator">
          <span>{{ auth.user?.displayName || auth.user?.username }}</span>
          <el-tag size="small" effect="plain">{{ auth.role }}</el-tag>
          <el-button :icon="SwitchButton" text @click="logout">退出</el-button>
        </div>
      </header>
      <section class="page-stage">
        <RouterView />
      </section>
    </main>
  </div>
</template>
