<template>
  <a-layout :class="['school-layout', { 'is-collapsed': collapsed }]">
    <a-layout-sider v-model:collapsed="collapsed" :trigger="null" collapsible class="school-sider">
      <div class="logo">
        <img src="/logo/logo.png" alt="Logo" class="logo-img" />
        <div v-if="!collapsed" class="logo-text">
          <span class="logo-tenant">{{ tenantName }}</span>
          <span class="logo-title">少儿智慧阅读</span>
          <span class="logo-subtitle">管理后台</span>
        </div>
      </div>

      <div class="sider-menu-wrapper">
        <a-menu v-model:selectedKeys="selectedKeys" v-model:openKeys="openKeys" mode="inline" theme="light"
          :inline-collapsed="collapsed" @click="handleMenuClick" class="side-menu">
          <!-- 数据概览 - 独立一级菜单 -->
          <a-menu-item key="dashboard">
            <template #icon>
              <DashboardOutlined />
            </template>
            <span>数据概览</span>
          </a-menu-item>

          <!-- 人员管理 -->
          <a-sub-menu key="staff">
            <template #icon>
              <TeamOutlined />
            </template>
            <template #title>人员管理</template>
            <a-menu-item key="teachers">
              <template #icon>
                <SolutionOutlined />
              </template>
              <span>教师管理</span>
            </a-menu-item>
            <a-menu-item key="students">
              <template #icon>
                <UserOutlined />
              </template>
              <span>学生管理</span>
            </a-menu-item>
            <a-menu-item key="parents">
              <template #icon>
                <IdcardOutlined />
              </template>
              <span>家长管理</span>
            </a-menu-item>
            <a-menu-item key="classes">
              <template #icon>
                <HomeOutlined />
              </template>
              <span>班级管理</span>
            </a-menu-item>
          </a-sub-menu>

          <!-- 教学管理 -->
          <a-sub-menu key="teaching">
            <template #icon>
              <BookOutlined />
            </template>
            <template #title>教学管理</template>
            <a-menu-item key="courses">
              <template #icon>
                <ReadOutlined />
              </template>
              <span>课程中心</span>
            </a-menu-item>
            <a-menu-item key="school-courses">
              <template #icon>
                <FolderAddOutlined />
              </template>
              <span>校本课程包</span>
            </a-menu-item>
            <a-menu-item key="schedule">
              <template #icon>
                <CalendarOutlined />
              </template>
              <span>课程排期</span>
            </a-menu-item>
            <a-menu-item key="tasks">
              <template #icon>
                <CheckSquareOutlined />
              </template>
              <span>阅读任务</span>
            </a-menu-item>
            <a-menu-item key="task-templates">
              <template #icon>
                <CopyOutlined />
              </template>
              <span>任务模板</span>
            </a-menu-item>
            <a-menu-item key="feedback">
              <template #icon>
                <MessageOutlined />
              </template>
              <span>课程反馈</span>
            </a-menu-item>
          </a-sub-menu>

          <!-- 数据中心 -->
          <a-sub-menu key="data">
            <template #icon>
              <BarChartOutlined />
            </template>
            <template #title>数据中心</template>
            <a-menu-item key="reports">
              <template #icon>
                <FileTextOutlined />
              </template>
              <span>数据报告</span>
            </a-menu-item>
            <a-menu-item key="growth">
              <template #icon>
                <FileImageOutlined />
              </template>
              <span>成长档案</span>
            </a-menu-item>
          </a-sub-menu>

          <!-- 系统管理 -->
          <a-sub-menu key="system">
            <template #icon>
              <SettingOutlined />
            </template>
            <template #title>系统管理</template>
            <a-menu-item key="packages">
              <template #icon>
                <GiftOutlined />
              </template>
              <span>套餐管理</span>
            </a-menu-item>
            <a-menu-item key="operation-logs">
              <template #icon>
                <HistoryOutlined />
              </template>
              <span>操作日志</span>
            </a-menu-item>
            <a-menu-item key="settings">
              <template #icon>
                <ToolOutlined />
              </template>
              <span>系统设置</span>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </div>
      <div class="sider-version" :title="`版本 v${appVersion}`">
        <span>v{{ appVersion }}</span>
      </div>
    </a-layout-sider>

    <a-layout>
      <a-layout-header class="school-header">
        <div class="header-left">
          <MenuUnfoldOutlined v-if="collapsed" class="trigger" @click="collapsed = !collapsed" />
          <MenuFoldOutlined v-else class="trigger" @click="collapsed = !collapsed" />
        </div>

        <div class="header-right">
          <a-space>
            <a-dropdown>
              <a-space class="user-info" style="cursor: pointer;">
                <a-avatar :size="32" class="user-avatar">
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                <span class="user-name">{{ userName }}</span>
                <DownOutlined />
              </a-space>
              <template #overlay>
                <a-menu @click="handleUserMenuClick">
                  <a-menu-item key="profile">
                    <UserOutlined />
                    个人信息
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="logout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </div>
      </a-layout-header>

      <a-layout-content class="school-content">
        <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 { message } from 'ant-design-vue';
import {
  DashboardOutlined,
  TeamOutlined,
  UserOutlined,
  HomeOutlined,
  BookOutlined,
  GiftOutlined,
  FileTextOutlined,
  FileImageOutlined,
  CheckSquareOutlined,
  CopyOutlined,
  MessageOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  LogoutOutlined,
  DownOutlined,
  SettingOutlined,
  CalendarOutlined,
  HistoryOutlined,
  SolutionOutlined,
  ReadOutlined,
  BarChartOutlined,
  ToolOutlined,
  IdcardOutlined,
  FolderAddOutlined,
} from '@ant-design/icons-vue';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const appVersion = __APP_VERSION__;

const collapsed = ref(false);
const selectedKeys = ref(['dashboard']);
const openKeys = ref<string[]>(['staff', 'teaching', 'data', 'system']);
const notifications = ref(0);

const userName = computed(() => userStore.user?.name || '管理员');
const tenantName = computed(() => userStore.user?.tenantName || '');

// 路由到菜单的映射关系
const routeToMenuMap: Record<string, { key: string; parentKey: string }> = {
  '/school/teachers': { key: 'teachers', parentKey: 'staff' },
  '/school/students': { key: 'students', parentKey: 'staff' },
  '/school/parents': { key: 'parents', parentKey: 'staff' },
  '/school/classes': { key: 'classes', parentKey: 'staff' },
  '/school/courses': { key: 'courses', parentKey: 'teaching' },
  '/school/school-courses': { key: 'school-courses', parentKey: 'teaching' },
  '/school/schedule': { key: 'schedule', parentKey: 'teaching' },
  '/school/tasks': { key: 'tasks', parentKey: 'teaching' },
  '/school/task-templates': { key: 'task-templates', parentKey: 'teaching' },
  '/school/feedback': { key: 'feedback', parentKey: 'teaching' },
  '/school/reports': { key: 'reports', parentKey: 'data' },
  '/school/growth': { key: 'growth', parentKey: 'data' },
  '/school/package': { key: 'packages', parentKey: 'system' },
  '/school/operation-logs': { key: 'operation-logs', parentKey: 'system' },
  '/school/settings': { key: 'settings', parentKey: 'system' },
};

// 根据路由设置选中的菜单
watch(
  () => route.path,
  (path) => {
    const menuInfo = routeToMenuMap[path];
    if (menuInfo) {
      selectedKeys.value = [menuInfo.key];
      // 确保父菜单展开
      if (!openKeys.value.includes(menuInfo.parentKey)) {
        openKeys.value = [...openKeys.value, menuInfo.parentKey];
      }
    } else if (path === '/school' || path === '/school/dashboard') {
      selectedKeys.value = ['dashboard'];
    } else if (path.startsWith('/school/profile')) {
      selectedKeys.value = [];
    }
  },
  { immediate: true }
);

const handleMenuClick = ({ key }: { key: string | number }) => {
  const keyStr = String(key);
  if (keyStr === 'packages') {
    router.push('/school/package');
  } else if (keyStr === 'operation-logs') {
    router.push('/school/operation-logs');
  } else if (!['staff', 'teaching', 'data', 'system'].includes(keyStr)) {
    // 只有点击叶子菜单项才跳转
    router.push(`/school/${keyStr}`);
  }
};

const handleUserMenuClick = ({ key }: { key: string | number }) => {
  const keyStr = String(key);
  if (keyStr === 'logout') {
    userStore.logout();
    message.success('退出成功');
    router.push('/login');
  } else if (keyStr === 'profile') {
    router.push('/school/profile');
  }
};
</script>

<style scoped lang="scss">
// 少儿阅读主题配色
$primary-color: #FF8C42; // 温暖的橙色
$primary-light: #FFF4EC;
$primary-dark: #E67635;
$accent-color: #4CAF50; // 生机绿色
$text-color: #333333;
$text-secondary: #666666;
$border-color: #E8E8E8;
$bg-light: #FAFAFA;

.school-layout {
  min-height: 100vh;
  background: $bg-light;
  position: relative;
  padding-left: 200px; // 侧边栏默认宽度
  padding-top: 64px; // 预留顶部栏高度
}

.school-layout.is-collapsed {
  padding-left: 80px; // 菜单收起后的宽度
}

.school-sider {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
  background: white !important;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);
  border-right: 1px solid $border-color;
  display: flex;
  flex-direction: column;

  .logo {
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12px 16px;
    border-bottom: 1px solid $border-color;
    background: linear-gradient(135deg, $primary-light 0%, white 100%);

    .logo-img {
      width: 44px;
      height: 44px;
      object-fit: contain;
      flex-shrink: 0;
    }

    .logo-text {
      display: flex;
      flex-direction: column;
      margin-left: 12px;
      line-height: 1.4;
      max-width: 140px;

      .logo-tenant {
        font-size: 13px;
        font-weight: 600;
        color: $primary-color;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .logo-title {
        font-size: 14px;
        font-weight: 600;
        color: $text-color;
        white-space: nowrap;
      }

      .logo-subtitle {
        font-size: 11px;
        color: $text-secondary;
        white-space: nowrap;
      }
    }
  }

  .side-menu {
    border-right: none !important;
    padding: 8px 12px;

    :deep(.ant-menu-item) {
      margin: 4px 0;
      padding-left: 12px !important;
      padding-right: 12px !important;
      border-radius: 8px;
      height: 44px;
      line-height: 44px;
      color: $text-color;
      transition: all 0.3s;
      display: flex;
      align-items: center;

      .ant-menu-title-content {
        display: flex;
        align-items: center;
      }

      &:hover {
        background: $primary-light;
        color: $primary-color;
      }

      &.ant-menu-item-selected {
        background: linear-gradient(135deg, $primary-color 0%, $primary-dark 100%);
        color: white;

        &::after {
          display: none;
        }

        .anticon {
          color: white;
        }
      }
    }

    // 子菜单标题样式
    :deep(.ant-menu-submenu-title) {
      margin: 4px 0;
      padding-left: 12px !important;
      padding-right: 12px !important;
      border-radius: 8px;
      height: 44px;
      line-height: 44px;
      color: $text-color;
      transition: all 0.3s;

      &:hover {
        background: $primary-light;
        color: $primary-color;
      }
    }

    // 展开的子菜单标题
    :deep(.ant-menu-submenu-open > .ant-menu-submenu-title) {
      color: $primary-color;
      font-weight: 500;
    }

    // 子菜单内容区域
    :deep(.ant-menu-sub) {
      background: transparent;
      padding-left: 8px !important;

      .ant-menu-item {
        height: 40px;
        line-height: 40px;
        margin: 2px 0;
        padding-left: 44px !important;
        font-size: 13px;
      }
    }
  }
}

.sider-menu-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;

  // 自定义侧边栏滚动条样式
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.6);
    border-radius: 999px;
  }
}

.sider-version {
  padding: 10px 12px 14px;
  border-top: 1px solid $border-color;
  font-size: 12px;
  color: #9CA3AF;
  text-align: center;
  line-height: 1.2;
  background: #fff;
  flex-shrink: 0;
}

.school-header {
  background: white;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  border-bottom: 1px solid $border-color;
  position: fixed;
  top: 0;
  left: 200px;
  right: 0;
  z-index: 90;

  .trigger {
    font-size: 18px;
    cursor: pointer;
    transition: color 0.3s;
    color: $text-secondary;

    &:hover {
      color: $primary-color;
    }
  }

  .user-info {
    padding: 0 12px;
  }

  .user-avatar {
    background: linear-gradient(135deg, $primary-color 0%, $primary-dark 100%);
  }

  .user-name {
    color: $text-color;
    font-weight: 500;
  }
}

.school-layout.is-collapsed .school-header {
  left: 80px;
}

.school-content {
  margin: 20px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  min-height: calc(100vh - 64px - 40px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
</style>
