<template>
  <v-app>
    <!--
      装饰背景：position: fixed 让它严格按视口尺寸铺满，不会像 v-img+cover
      那样被图片自身宽高比撑高（那样会撑到 width × (image.h/image.w) =
      1128px+，让页面能往下滚动到 footer 之下的空白背景）。
      真正的白色半透明蒙层在 v-layout 上，所以图片仍以 ~15% 透明度透出。
    -->
    <div class="app-bg" aria-hidden="true"></div>
    <v-layout min-height="100dvh" class="app-content">
      <AppHeader :drawer-active="drawerActive" @toggle-drawer="toggleDrawer" @logout="showLogoutDialog = true" />
      <AppFooter />
      <AppDrawer v-model="drawerActive" />
      <v-main>
        <v-container fluid class="pt-4 pb-0">
          <v-breadcrumbs :items="breadcrumbs">
            <template #item="{ item }">
              <v-breadcrumbs-item
                :disabled="item.disabled"
                :to="item.to"
                :exact="true"
              >
                <v-icon v-if="item.icon" :icon="item.icon" size="small" class="me-1" />
                {{ item.title }}
              </v-breadcrumbs-item>
            </template>
          </v-breadcrumbs>
        </v-container>
        <slot></slot>
      </v-main>
    </v-layout>
    <!-- 登出确认对话框 -->
    <v-dialog v-model="showLogoutDialog" max-width="400">
      <v-card>
        <v-card-title>{{ $t('components.appHeader.logoutDialog.title') }}</v-card-title>
        <v-card-text>{{ $t('components.appHeader.logoutDialog.message') }}</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn color="primary" text @click="showLogoutDialog = false">{{ $t('components.appHeader.logoutDialog.cancel') }}</v-btn>
          <v-btn color="primary" text @click="confirmLogout">{{ $t('components.appHeader.logoutDialog.confirm') }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-app>
</template>

<script setup>
import { ref, watchEffect, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDisplay } from 'vuetify'
import AppHeader from './AppHeader.vue'
import AppDrawer from './AppDrawer.vue'
import AppFooter from './AppFooter.vue'

import { useAuthStore } from '../stores/auth'
import { useRouter, useRoute } from 'vue-router'
import { GLOBAL_MENU_ITEMS } from './constants/menuItems'

const { t } = useI18n()
const { lgAndUp } = useDisplay()
const auth = useAuthStore()
const router = useRouter()
const route = useRoute()

const drawerActive = ref(false)
const toggleDrawer = () => { drawerActive.value = !drawerActive.value }

// 桌面 (≥1280px) 默认展开 Drawer; 移动端由 hamburger 触发
watchEffect(() => {
  drawerActive.value = lgAndUp.value
})

const showLogoutDialog = ref(false)
const confirmLogout = () => {
  showLogoutDialog.value = false
  handleLogout()
}
const handleLogout = () => {
  // 1. 调用 Pinia 的登出方法
  auth.logout && auth.logout()

  // 2. 清除 localStorage/sessionStorage（如有）
  localStorage.removeItem('token')
  sessionStorage.removeItem('token')

  // 3. 跳转到登录页
  router.push('/login')
}

// 从菜单配置中查找图标的辅助函数
const findIconByPath = (items, path) => {
  for (const item of items) {
    if (item.path === path && item.mdiIcon) return item.mdiIcon
    if (item.children) {
      const childIcon = findIconByPath(item.children, path)
      if (childIcon) return childIcon
    }
  }
  return null
}

const breadcrumbs = computed(() => {
  // 如果路由meta中定义了breadcrumbPath，直接使用
  if (route.meta.breadcrumbPath) {
    return route.meta.breadcrumbPath.map((item, index) => {
      const breadcrumbItem = {
        title: t(item.key),
        to: item.to,
        disabled: item.disabled
      }

      // 为首页添加home图标
      if (index === 0 && item.key === 'navigation.breadcrumb.home') {
        breadcrumbItem.icon = 'mdi-home'
      }
      // 为基础数据层级添加数据库图标
      else if (item.key === 'navigation.breadcrumb.masterData') {
        breadcrumbItem.icon = 'mdi-database-outline'
      }
      // 为当前页面（最后一项）添加页面特定图标
      else if (index === route.meta.breadcrumbPath.length - 1) {
        // 优先使用路由meta中定义的图标
        if (route.meta.breadcrumb?.icon) {
          breadcrumbItem.icon = route.meta.breadcrumb.icon
        } else {
          // 从菜单配置中查找图标
          const pageIcon = findIconByPath(GLOBAL_MENU_ITEMS, route.path)
          if (pageIcon) {
            breadcrumbItem.icon = pageIcon
          }
        }
      }

      return breadcrumbItem
    })
  }

  // 默认情况下，根据路径生成简单面包屑
  const path = route.path

  if (path === '/') {
    return [{
      title: t('navigation.breadcrumb.home'),
      to: '/',
      disabled: true,
      icon: 'mdi-home'
    }]
  }

  // 如果没有定义breadcrumbPath，返回默认面包屑
  return [{
    title: t('navigation.breadcrumb.home'),
    to: '/',
    disabled: true,
    icon: 'mdi-home'
  }]
})


</script>

<style scoped>
/*
 * 背景图片：固定在视口，覆盖整屏；用 background-image 替代 <v-img cover>，
 * 避免 v-img 的 v-responsive 容器按图片自身宽高比撑高（width × 2333/3500 ≈
 * 1128px），导致页面能滚到 footer 之下。
 * pointer-events: none — 不抢交互。
 */
.app-bg {
  position: fixed;
  inset: 0;
  z-index: 0;
  background: url('@/assets/images/login.jpg') center top / cover no-repeat;
  pointer-events: none;
}

/*
 * v-layout 的白色半透明蒙层从 inline style 挪到这里（也保留 rgba 不变）。
 * 加 position: relative + z-index: 1，让内容层在 .app-bg 之上，
 * 否则 v-app 的 flex 排版可能把 .app-bg 盖住。
 */
.app-content {
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.85);
}
</style>
