<template>
  <a-layout class="layout-container">
    <a-layout-header class="layout-header">
      <div class="logo" :style="{ width: isCollapsed ? '48px' : '240px', padding: isCollapsed ? '0' : '0 20px' }">
        <img :src="isCollapsed ? logoLittleSrc : logoSrc" alt="Logo" class="logo-img" :style="{ marginRight: isCollapsed ? '0' : '8px' }" />
        <span class="logo-text" v-show="!isCollapsed">能耗管理平台</span>
      </div>
      <div class="header-content">
        <a-breadcrumb>
          <a-breadcrumb-item v-for="item in route.matched" :key="item.path">
            {{ item.meta?.title || item.name }}
          </a-breadcrumb-item>
        </a-breadcrumb>
        <div class="user-info">
          <a-dropdown @select="handleCommand">
            <div class="user-dropdown-trigger" style="display: flex; align-items: center; cursor: pointer; color: var(--color-text-1);">
              <a-avatar :size="32" style="background-color: #3370ff">
                <IconUser />
              </a-avatar>
              <span style="margin-left: 8px; margin-right: 8px;">{{ userStore.user?.Name || userStore.user?.name || 'Admin' }}</span>
              <icon-down />
            </div>
            <template #content>
              <a-doption value="profile">用户设置</a-doption>
              <a-doption value="logout">退出登录</a-doption>
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>
    <a-layout style="height: calc(100vh - 60px); overflow: hidden;">
      <a-layout-sider
        collapsible
        breakpoint="xl"
        :width="240"
        style="height: 100%; background-color: #fff;"
        @collapse="onCollapse"
      >
        <a-menu
          :default-selected-keys="[$route.path]"
          :default-open-keys="openKeys"
          @menu-item-click="handleMenuClick"
          :style="{ width: '100%' }"
          :theme="'light'"
        >
        <template v-for="menu in permissionStore.sidebarMenus" :key="menu.path">
          <!-- If it has children and is a Directory (M) or Menu (C) -->
          <a-sub-menu v-if="menu.children && menu.children.length > 0" :key="resolvePath(menu.path)">
            <template #title>
              <!-- 暂时简单处理 icon，后续可能需要映射 Element Icon 到 Arco Icon -->
              <component :is="getIcon(menu.icon)" v-if="menu.icon" class="menu-icon" />
              <span v-else class="icon-placeholder"></span> 
              {{ menu.name }}
            </template>
            
            <template v-for="child in menu.children" :key="child.path">
               <a-sub-menu v-if="child.children && child.children.length > 0" :key="resolvePath(child.path, menu.path)">
                  <template #title>
                      <component :is="getIcon(child.icon)" v-if="child.icon" class="menu-icon" />
                      <span v-else-if="!isCollapsed" class="icon-placeholder"></span>
                      {{ child.name }}
                  </template>
                  <a-menu-item 
                      v-for="grandchild in child.children" 
                      :key="resolvePath(grandchild.path, menu.path + '/' + child.path)"
                  >
                      <component :is="getIcon(grandchild.icon)" v-if="grandchild.icon" class="menu-icon" />
                      <span v-else-if="!isCollapsed" class="icon-placeholder"></span>
                      {{ grandchild.name }}
                  </a-menu-item>
               </a-sub-menu>

              <a-menu-item v-else :key="resolvePath(child.path, menu.path)">
                  <component :is="getIcon(child.icon)" v-if="child.icon" class="menu-icon" />
                  <span v-else-if="!isCollapsed" class="icon-placeholder"></span>
                  {{ child.name }}
              </a-menu-item>
            </template>
          </a-sub-menu>

          <!-- If it has no children (Leaf node) -->
          <a-menu-item v-else :key="resolvePath(menu.path)">
            <component :is="getIcon(menu.icon)" v-if="menu.icon" class="menu-icon" />
            <span v-else class="icon-placeholder"></span>
            {{ menu.name }}
          </a-menu-item>
        </template>
      </a-menu>
    </a-layout-sider>
    <a-layout-content class="layout-content">
      <router-view />
    </a-layout-content>
  </a-layout>
  </a-layout>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { usePermissionStore } from '../stores/permission';
import { useUserStore } from '../stores/user';
import { useRouter, useRoute } from 'vue-router';
// 引入基础图标，实际项目中建议全局注册或动态加载
import { IconUser, IconDown, IconApps, IconDashboard, IconBarChart, IconBook, IconSettings } from '@arco-design/web-vue/es/icon';
import logoSrc from '../logo.png';
import logoLittleSrc from '../logo_little.svg';

const permissionStore = usePermissionStore();
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const isCollapsed = ref(false);

const resolvePath = (routePath: string, basePath?: string) => {
  if (routePath.startsWith('/')) {
    return routePath;
  }
  if (basePath) {
    return `${basePath}/${routePath}`.replace('//', '/');
  }
  return routePath;
};

// 计算展开的菜单
const openKeys = computed(() => {
    const matched = route.matched;
    return matched.map(item => item.path);
});

const handleMenuClick = (key: string) => {
    router.push(key);
};

const handleCommand = (value: string | number | Record<string, any> | undefined) => {
  if (value === 'logout') {
    userStore.logout();
    router.push('/login');
  } else if (value === 'profile') {
    router.push('/personal/profile');
  }
};

const onCollapse = (val: boolean) => {
  isCollapsed.value = val;
};

// 简单的图标映射 helper
const getIcon = (iconName: string) => {
    if (!iconName) return null;
    const icons: Record<string, any> = {
        IconApps,
        IconDashboard,
        IconBarChart,
        IconBook,
        IconSettings,
        IconUser,
        IconDown
    };
    if (icons[iconName]) return icons[iconName];
    // Fallback if dynamic name is used but not explicitly in map (though in script setup we need the object)
    return null;
};

</script>

<style scoped>
.layout-container {
  height: 100vh;
}
.layout-header {
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  height: 60px;
  line-height: 60px;
  padding: 0;
  display: flex;
}
.layout-content {
  padding: 20px;
  background-color: var(--color-fill-2);
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
}


.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text-1);
  background-color: var(--color-bg-2);
  padding: 0 20px;
  overflow: hidden;
  width: 240px;
  flex-shrink: 0;
  border-right: 1px solid var(--color-border);
  box-sizing: border-box;
}

.logo-img {
  width: auto;
  height: 32px;
  margin-right: 8px;
}

.logo-text {
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  color: rgb(32, 39, 53);
}


.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  flex: 1;
  padding: 0 20px;
}
.user-info {
  display: flex;
  align-items: center;
}
.icon-placeholder {
  display: inline-block;
  width: 1em;
  height: 1em;
  margin-right: 10px;
}

/* Sidebar Menu Overrides to match Arco Theme 15061 */
:deep(.arco-menu-light .arco-menu-item),
:deep(.arco-menu-light .arco-menu-group-title),
:deep(.arco-menu-light .arco-menu-pop-header),
:deep(.arco-menu-light .arco-menu-inline-header) {
  color: rgb(104, 111, 120); /* @color-text-2 */
  font-size: 14px;
  line-height: 40px; /* Adjust line height for better spacing */
}

:deep(.arco-menu-light .arco-menu-item),
:deep(.arco-menu-light .arco-menu-inline-header) {
   margin-bottom: 4px; /* Slight spacing between items */
   border-radius: 4px; /* @border-radius-medium approx */
}

:deep(.arco-menu-light .arco-menu-item:not(.arco-menu-selected):hover) {
  background-color: rgb(245, 245, 245); /* @color-fill-2 */
  color: rgb(32, 39, 53); /* Darker text on hover if desired, or keep original */
}

:deep(.arco-menu-light .arco-menu-item.arco-menu-selected) {
  color: rgb(0, 85, 255); /* @primary-6 */
  background-color: rgb(232, 244, 255); /* @primary-1 / link-1 */
  font-weight: 500;
}

:deep(.menu-icon) {
  margin-right: 10px; /* Adjust icon spacing */
  color: inherit; /* Icons follow text color */
  font-size: 16px;
}

/* Force align the expand/collapse arrow to the right */
:deep(.arco-menu-inline-header .arco-menu-icon-suffix) {
  right: 16px;
  position: absolute;
}

/* Ensure Logo text matches theme text color 1 */
.logo-text {
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  color: rgb(32, 39, 53); /* @color-text-1 */
}

/* Sidebar background force white */
.layout-container :deep(.arco-layout-sider) {
    background-color: #fff;
    box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05); /* Slight shadow for depth */
    z-index: 100;
}

.layout-container :deep(.arco-layout-sider-children) {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
}
</style>

<style>
/* 全局滚动条样式，确保覆盖所有子元素 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: transparent;
}
</style>
