<template>
  <a-layout class="layout">
    <a-layout-sider
      v-if="!hideSidebar"
      v-model:collapsed="collapsed"
      :width="200"
      class="custom-sider"
    >
      <div class="sider-content">
        <div class="sider-top">
          <div class="logo">
            <img v-if="!collapsed" src="../assets/images/logo.png" alt="" />
            <!-- <h2 v-if="!collapsed" class="logo-text">比赛管理系统</h2> -->
            <h2 v-else class="logo-text">CMS</h2>
          </div>
          <a-menu
            v-model:selectedKeys="selectedKeys"
            v-model:openKeys="openKeys"
            mode="inline"
            class="custom-menu"
            :items="menuItems"
            @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,
} 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
})

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

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 fullUrl = `${window.location.origin}/${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: #1890ff;
$primary-dark: #0958d9;
$primary-light: #40a9ff;

.layout {
  min-height: 100vh;
}

// 渐变主题风格侧边栏
.custom-sider {
  background: #fff !important;
  border-right: none !important;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.05);

  :deep(.ant-layout-sider-children) {
    background: #fff;
    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 8px;
}

// Logo 区域 - 简洁风格
.logo {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;

  img {
    max-width: 100%;
    max-height: 32px;
    object-fit: contain;
  }

  .logo-text {
    color: $primary;
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    letter-spacing: 1px;
  }
}

// 底部用户区域
.sider-bottom {
  padding: 12px 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  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: 8px;
    cursor: pointer;
    transition: all 0.3s;
    flex: 1;
    min-width: 0;

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

    :deep(.ant-avatar) {
      border: 2px solid rgba($primary, 0.2);
    }

    .username {
      font-size: 14px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      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: 8px;
    cursor: pointer;
    transition: all 0.3s;
    color: rgba(0, 0, 0, 0.45);
    flex-shrink: 0;

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

.sider-bottom-collapsed {
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 12px 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: rgba(0, 0, 0, 0.75);
    margin: 4px 0;
    border-radius: 10px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    background: transparent !important;
    height: 44px;
    line-height: 44px;

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

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

      .anticon {
        color: $primary;
      }
    }

    &.ant-menu-item-selected {
      color: #fff !important;
      background: linear-gradient(135deg, $primary 0%, $primary-dark 100%) !important;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba($primary, 0.3);

      .anticon {
        color: #fff;
      }

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

  :deep(.ant-menu-submenu) {
    .ant-menu-submenu-title {
      color: rgba(0, 0, 0, 0.75);
      margin: 4px 0;
      border-radius: 10px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      background: transparent !important;
      height: 44px;
      line-height: 44px;

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

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

        .anticon {
          color: $primary;
        }
      }
    }

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

      .anticon {
        color: $primary;
      }
    }

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

  :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 {
        background: linear-gradient(135deg, $primary 0%, $primary-dark 100%) !important;
        box-shadow: 0 2px 8px rgba($primary, 0.3);
      }
    }
  }

  // 展开箭头样式
  :deep(.ant-menu-submenu-arrow) {
    color: rgba(0, 0, 0, 0.45);
    transition: all 0.3s;
  }

  :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: 20px;
  background: #f5f7fa;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
}

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