<template>
  <a-layout class="layout">
    <a-layout-sider
      v-if="!hideSidebar"
      v-model:collapsed="collapsed"
      :width="210"
      class="custom-sider"
    >
      <div class="sider-content">
        <div class="sider-top">
          <div class="logo" :class="{ 'logo-collapsed': collapsed }">
            <img src="../assets/images/logo-icon.png" alt="乐绘世界" class="logo-img" />
            <div v-if="!collapsed" class="logo-text">
              <span class="logo-title-main">乐绘世界</span>
              <span class="logo-title-sub">创想活动乐园</span>
            </div>
          </div>
          <!-- 3D建模实验室快捷入口（仅学生和教师可见） -->
          <div
            v-if="canAccess3DLab"
            class="lab-entry"
            :class="{ 'lab-entry-collapsed': collapsed }"
            @click="open3DLab"
          >
            <div class="lab-entry-icon">
              <experiment-outlined />
            </div>
            <div v-if="!collapsed" class="lab-entry-content">
              <span class="lab-entry-title">3D建模实验室</span>
              <span class="lab-entry-desc">AI智能建模</span>
            </div>
            <div v-if="!collapsed" class="lab-entry-arrow">
              <right-outlined />
            </div>
          </div>
          <a-menu
            v-model:selectedKeys="selectedKeys"
            v-model:openKeys="openKeys"
            mode="inline"
            class="custom-menu"
            :items="filteredMenuItems"
            @click="handleMenuClick"
          />
        </div>
        <div
          class="sider-bottom"
          :class="{ 'sider-bottom-collapsed': collapsed }"
        >
          <a-dropdown placement="topRight">
            <div
              class="user-info"
              :class="{ 'user-info-collapsed': collapsed }"
            >
              <a-avatar :size="32" :src="userAvatar" />
              <span v-if="!collapsed" class="username">{{
                authStore.user?.nickname
              }}</span>
            </div>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="handleLogout">
                  <logout-outlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <div class="collapse-trigger" @click="collapsed = !collapsed">
            <menu-unfold-outlined v-if="collapsed" />
            <menu-fold-outlined v-else />
          </div>
        </div>
      </div>
    </a-layout-sider>
    <a-layout class="main-layout">
      <a-layout-content
        class="content"
        :class="{ 'content-fullscreen': hideSidebar }"
      >
        <router-view />
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue"
import { useRouter, useRoute } from "vue-router"
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
  ExperimentOutlined,
  RightOutlined,
} from "@ant-design/icons-vue"
import { useAuthStore } from "@/stores/auth"
import { convertMenusToMenuItems } from "@/utils/menu"
import { getUserAvatar } from "@/utils/avatar"
import type { MenuProps } from "ant-design-vue"

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const collapsed = ref(false)
const selectedKeys = ref<string[]>([])
const openKeys = ref<string[]>([])

// 生成用户头像URL（使用DiceBear API自动生成默认头像）
const userAvatar = computed(() => getUserAvatar(authStore.user))

// 根据路由 meta 判断是否隐藏侧边栏
const hideSidebar = computed(() => {
  return route.meta?.hideSidebar === true
})

// 判断是否可以访问3D建模实验室（仅学生和教师角色可见）
const canAccess3DLab = computed(() => {
  return authStore.hasAnyRole(["student", "teacher"])
})

// 使用动态菜单
const menuItems = computed<MenuProps["items"]>(() => {
  if (authStore.menus && authStore.menus.length > 0) {
    return convertMenusToMenuItems(authStore.menus)
  }
  // 如果没有菜单数据，返回空数组（或者可以返回默认菜单）
  return []
})

// 过滤掉3D建模实验室的菜单项（仅当用户能看到快捷入口时才过滤，避免重复显示）
const filteredMenuItems = computed<MenuProps["items"]>(() => {
  const items = menuItems.value || []
  // 如果用户能看到快捷入口，则过滤掉菜单中的3D实验室
  if (canAccess3DLab.value) {
    return items.filter((item: any) => {
      // 检查是否是3D建模实验室菜单
      const is3DLab =
        item?.key?.toLowerCase().includes("3dlab") ||
        item?.key?.toLowerCase().includes("3d-lab") ||
        item?.label?.includes("3D建模") ||
        item?.title?.includes("3D建模")
      return !is3DLab
    })
  }
  return items
})

// 打开3D建模实验室（当前窗口跳转，更快）
const open3DLab = () => {
  const tenantCode = route.params.tenantCode as string
  router.push(`/${tenantCode}/workbench/3d-lab`)
}

watch(
  () => route.name,
  (routeName) => {
    if (routeName) {
      selectedKeys.value = [routeName as string]
      // 自动展开包含当前路由的父菜单
      const findParentKeys = (
        menus: any[],
        targetName: string,
        parentKeys: string[] = [],
      ): string[] => {
        for (const menu of menus) {
          const menuKey = menu.key
          if (menuKey === targetName) {
            return parentKeys
          }
          if (menu.children && menu.children.length > 0) {
            const found = findParentKeys(menu.children, targetName, [
              ...parentKeys,
              menuKey,
            ])
            if (found.length > 0) return found
          }
        }
        return []
      }
      const parentKeys = findParentKeys(
        menuItems.value || [],
        routeName as string,
      )
      if (parentKeys.length > 0) {
        openKeys.value = parentKeys
      }
    }
  },
  { immediate: true },
)

const handleMenuClick = ({ key }: { key: string }) => {
  const tenantCode = route.params.tenantCode as string

  // 调试日志
  console.log("点击菜单，key:", key)

  // 检查是否是3D建模实验室菜单
  // 方法1: 检查key是否包含3D相关字符（考虑到路由名称的生成规则）
  // 路径 /workbench/3d-lab 会生成类似 Workbench3dLab 的key
  const is3DLab =
    key.toLowerCase().includes("3dlab") ||
    key.toLowerCase().includes("3d-lab") ||
    (key.toLowerCase().includes("workbench") &&
      key.toLowerCase().includes("3d"))

  // 方法2: 从菜单数据中查找对应的菜单项，检查path
  const findMenuByKey = (menus: any[], targetKey: string): any => {
    for (const menu of menus) {
      if (menu.key === targetKey) {
        return menu
      }
      if (menu.children) {
        const found = findMenuByKey(menu.children, targetKey)
        if (found) return found
      }
    }
    return null
  }

  const menuItem = findMenuByKey(menuItems.value || [], key)
  const is3DLabByPath =
    menuItem?.label?.includes("3D建模") || menuItem?.title?.includes("3D建模")

  // 调试日志
  console.log(
    "is3DLab:",
    is3DLab,
    "is3DLabByPath:",
    is3DLabByPath,
    "menuItem:",
    menuItem,
  )

  if (is3DLab || is3DLabByPath) {
    // 打开3D建模实验室页面（新窗口，路由配置了 hideSidebar 会自动隐藏侧边栏）
    console.log("检测到3D建模实验室，打开新窗口")
    const base = import.meta.env.BASE_URL || "/"
    const basePath = base.endsWith("/") ? base.slice(0, -1) : base
    const fullUrl = `${window.location.origin}${basePath}/${tenantCode}/workbench/3d-lab`
    window.open(fullUrl, "_blank")
    return
  }

  // 其他菜单项正常跳转
  if (tenantCode) {
    router.push({ name: key, params: { tenantCode } })
  } else {
    router.push({ name: key })
  }
}

const handleLogout = async () => {
  await authStore.logout()
  // 获取当前路由的租户编码，跳转到对应的登录页
  const tenantCode = route.params.tenantCode as string
  if (tenantCode) {
    router.push(`/${tenantCode}/login`)
  } else {
    router.push("/login")
  }
}
</script>

<style scoped lang="scss">
$primary: #6366f1;
$primary-dark: #4f46e5;
$primary-light: #818cf8;
$coral: #f97066;
$rose: #ec4899;

.layout {
  min-height: 100vh;
}

// ========== 侧边栏 ==========
.custom-sider {
  background: linear-gradient(180deg, #fefcfb 0%, #f8f5ff 100%) !important;
  border-right: 1px solid rgba(99, 102, 241, 0.06) !important;
  box-shadow: 2px 0 16px rgba(99, 102, 241, 0.06);

  :deep(.ant-layout-sider-children) {
    background: transparent;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.sider-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.sider-top {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 10px;

  &::-webkit-scrollbar {
    width: 3px;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(99, 102, 241, 0.15);
    border-radius: 3px;
  }
}

// ========== Logo 区域 ==========
.logo {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 26px 16px 22px;
  margin-bottom: 4px;
  cursor: default;

  .logo-img {
    width: 54px;
    height: 54px;
    object-fit: contain;
    flex-shrink: 0;
    transition: all 0.3s ease;
    filter: drop-shadow(0 2px 6px rgba(99, 102, 241, 0.15));
  }

  .logo-text {
    display: flex;
    flex-direction: column;
    gap: 3px;
    min-width: 0;
  }

  .logo-title-main {
    font-size: 16px;
    font-weight: 800;
    background: linear-gradient(135deg, #6366f1 0%, #ec4899 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    letter-spacing: 2px;
    line-height: 1.3;
  }

  .logo-title-sub {
    font-size: 11px;
    font-weight: 600;
    color: #9ca3af;
    letter-spacing: 3px;
    line-height: 1.3;
  }
}

.logo-collapsed {
  justify-content: center;
  padding: 26px 8px 22px;

  .logo-img {
    width: 42px;
    height: 42px;
  }
}

// ========== 3D建模实验室快捷入口 ==========
.lab-entry {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 4px 0 14px 0;
  padding: 12px 14px;
  background: linear-gradient(
    135deg,
    rgba($primary, 0.06) 0%,
    rgba($rose, 0.06) 100%
  );
  border: 1px solid rgba($primary, 0.12);
  border-radius: 14px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    background: linear-gradient(
      135deg,
      rgba($primary, 0.10) 0%,
      rgba($rose, 0.10) 100%
    );
    border-color: rgba($primary, 0.25);
    transform: translateY(-1px);
    box-shadow: 0 4px 14px rgba($primary, 0.12);
  }

  .lab-entry-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, $primary 0%, $rose 100%);
    border-radius: 10px;
    color: #fff;
    font-size: 17px;
    flex-shrink: 0;
  }

  .lab-entry-content {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;

    .lab-entry-title {
      font-size: 13px;
      font-weight: 700;
      color: #1e1b4b;
      line-height: 1.3;
    }

    .lab-entry-desc {
      font-size: 11px;
      color: #9ca3af;
      line-height: 1.2;
    }
  }

  .lab-entry-arrow {
    color: #9ca3af;
    font-size: 11px;
    transition: all 0.25s;
  }

  &:hover .lab-entry-arrow {
    color: $primary;
    transform: translateX(3px);
  }
}

.lab-entry-collapsed {
  justify-content: center;
  padding: 10px;
  margin: 4px 4px 14px 4px;

  .lab-entry-icon {
    width: 32px;
    height: 32px;
    font-size: 15px;
  }
}

// ========== 底部用户区域 ==========
.sider-bottom {
  padding: 14px 14px;
  border-top: 1px solid rgba(99, 102, 241, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;

  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 6px 10px;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.25s;
    flex: 1;
    min-width: 0;

    &:hover {
      background: rgba($primary, 0.06);
    }

    :deep(.ant-avatar) {
      border: 2px solid rgba($primary, 0.15);
      box-shadow: 0 2px 6px rgba($primary, 0.1);
    }

    .username {
      font-size: 13px;
      font-weight: 600;
      color: #374151;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .user-info-collapsed {
    justify-content: center;
    padding: 6px;
    flex: unset;
  }

  .collapse-trigger {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.25s;
    color: #9ca3af;
    flex-shrink: 0;

    &:hover {
      background: rgba($primary, 0.06);
      color: $primary;
    }
  }
}

.sider-bottom-collapsed {
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 14px 8px;

  .collapse-trigger {
    width: 100%;
  }
}

// ========== 覆盖 Ant Design 默认边框 ==========
:deep(.ant-menu-light.ant-menu-root.ant-menu-inline),
:deep(.ant-menu-light.ant-menu-root.ant-menu-vertical) {
  border-inline-end: none !important;
}

// ========== 菜单样式 ==========
.custom-menu {
  background: transparent !important;
  border-right: none !important;
  border-inline-end: none !important;
  padding: 4px 0;

  :deep(.ant-menu-item) {
    color: #374151;
    margin: 3px 0;
    border-radius: 12px;
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    background: transparent !important;
    height: 44px;
    line-height: 44px;
    font-weight: 500;

    .anticon {
      font-size: 16px;
      transition: all 0.25s;
    }

    &:hover {
      color: $primary !important;
      background: rgba($primary, 0.06) !important;
      transform: translateX(2px);

      .anticon {
        color: $primary;
      }
    }

    &.ant-menu-item-selected {
      color: $primary !important;
      background: linear-gradient(
        135deg,
        rgba($primary, 0.10) 0%,
        rgba($rose, 0.05) 100%
      ) !important;
      font-weight: 600;
      box-shadow: 0 2px 8px rgba($primary, 0.08);

      .anticon {
        color: $primary;
      }

      &::after {
        display: none;
      }
    }
  }

  :deep(.ant-menu-submenu) {
    .ant-menu-submenu-title {
      color: #374151;
      margin: 3px 0;
      border-radius: 12px;
      transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
      background: transparent !important;
      height: 44px;
      line-height: 44px;
      font-weight: 500;

      .anticon {
        font-size: 16px;
        transition: all 0.25s;
      }

      &:hover {
        color: $primary !important;
        background: rgba($primary, 0.06) !important;

        .anticon {
          color: $primary;
        }
      }
    }

    &.ant-menu-submenu-open > .ant-menu-submenu-title {
      color: $primary;
      background: rgba($primary, 0.06) !important;

      .anticon {
        color: $primary;
      }
    }

    &.ant-menu-submenu-selected > .ant-menu-submenu-title {
      color: $primary;
      font-weight: 600;
    }
  }

  :deep(.ant-menu-sub) {
    background: transparent !important;

    .ant-menu-item {
      padding-left: 48px !important;
      height: 40px;
      line-height: 40px;
      margin: 2px 0;

      &.ant-menu-item-selected {
        color: $primary !important;
        background: rgba($primary, 0.10) !important;
        box-shadow: none;

        .anticon {
          color: $primary;
        }
      }
    }
  }

  :deep(.ant-menu-submenu-arrow) {
    color: #9ca3af;
    transition: all 0.25s;
  }

  :deep(
    .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow
  ),
  :deep(
    .ant-menu-submenu:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow
  ) {
    color: $primary;
  }
}

// ========== 主内容区 ==========
.main-layout {
  height: 100vh;
  overflow: hidden;
}

.content {
  padding: 24px;
  background: #f8f7fc;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
}

.content-fullscreen {
  padding: 0;
  background: transparent;
}
</style>
