<template>
  <v-app>
    <v-img
      src="/src/assets/images/login.jpg"
      cover
      min-height="100dvh"
      style="object-position: center top;"
    >
      <v-layout min-height="100dvh" style="background: rgba(255, 255, 255, 0.85);">
        <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-img>
    <!-- 登出确认对话框 -->
    <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>
</style>
