<template>
  <div class="admin-layout">
    <aside class="admin-sidebar" :class="{ collapse: collapsed }">
      <div class="logo-bar">
        <SvgIcon name="logo" :size="22" color="#fff" />
        <span v-if="!collapsed" class="logo-text">康策CSM系统管理平台</span>
      </div>

      <NavBar
        ref="sideBarRef"
        class="side-menu"
        :routes="sideRoutes"
        :activeMenu="$route.path"
        :isIcon="false"
        :defaultOpeneds="defaultOpeneds"
      />

      <!-- <div class="collapse-btn" @click="toggleSidebar">
        <el-icon :size="14">
          <component :is="collapsed ? Expand : Fold" />
        </el-icon>
        <span v-if="!collapsed">收起导航</span>
      </div> -->
    </aside>

    <div class="admin-main">
      <header class="admin-header">
        <div class="header-title">{{ currentTitle }}</div>
        <div class="header-user">
          <el-dropdown trigger="hover" @command="handleCommand">
            <div class="user-trigger">
              <SvgIcon name="bell-filled" :size="20" />
              <el-avatar :size="28">管</el-avatar>
              <span class="username">{{ userStore.userInfo?.name || userStore.userInfo?.userName || '管理员' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item command="theme">更换主题</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>

      <main class="admin-content">
        <slot />
      </main>
    </div>

    <!-- 更换主题弹窗 -->
    <el-dialog
      v-model="themeDialogVisible"
      title="🎨 更换主题"
      width="540px"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <div class="theme-dialog">
        <div class="theme-grid">
          <div
            v-for="t in presetThemes"
            :key="t.value"
            class="theme-card"
            :class="{ active: themeStore.themeValue === t.value }"
            @click="handlePresetTheme(t.value)"
          >
            <div class="theme-preview" :style="{ background: t.preview }"></div>
            <div class="theme-name">{{ t.name }}</div>
            <div class="theme-desc">{{ t.desc }}</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessageBox } from "element-plus";
import { Fold, Expand, ArrowDown } from "@element-plus/icons-vue";
import NavBar from "@/components/navBar/NavBar.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { useUserStore } from "@/stores/api/user";
import { useThemeStore } from "@/stores/theme";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const themeStore = useThemeStore();
const collapsed = ref(false);

// 主题弹窗显隐
const themeDialogVisible = ref(false);

// 预设主题配置（与现有 scss 主题保持一致）
const presetThemes = [
  {
    value: "blue",
    name: "穹宇蓝",
    desc: "深邃星空，科技感十足",
    preview: "linear-gradient(135deg, #6c7cf3 0%, #5868e6 100%)",
  },
  {
    value: "purple",
    name: "星轨紫",
    desc: "神秘优雅，梦幻氛围",
    preview: "linear-gradient(135deg, #A06CFC 0%, #6B2EDB 100%)",
  },
  {
    value: "green",
    name: "青峦绿",
    desc: "清新自然，宁静致远",
    preview: "linear-gradient(135deg, #34B693 0%, #228F72 100%)",
  },
];

// 选择预设主题
const handlePresetTheme = (value) => {
  themeStore.setTheme(value);
};

// 菜单分组顺序（驱动侧边栏的顺序与分组）
const GROUP_ORDER = ["工单管理", "客户管理", "绩效管理", "系统管理"];

// 父级菜单的 icon（与 group 绑定）
const GROUP_ICON = {
  工单管理: "Tickets",
  客户管理: "OfficeBuilding",
  绩效管理: "Trophy",
  系统管理: "Setting",
};

// 父级菜单的 path 前缀（用第一个可见子项的 path 作为 index）
const buildSideRoutes = (children) => {
  const visible = children.filter((c) => c.meta?.title && !c.meta?.hidden);
  const groupMap = new Map();

  visible.forEach((c) => {
    const group = c.meta?.group;
    if (!group) return; // 顶路下未分组的子项不进入侧边栏（如 password）
    if (!groupMap.has(group)) groupMap.set(group, []);
    groupMap.get(group).push(c);
  });

  return GROUP_ORDER.filter((g) => groupMap.has(g)).map((group) => {
    const items = groupMap.get(group);
    return {
      // 父级 index 指向该组下第一个子项，这样点击父级会跳到默认页，
      // el-sub-menu 也能以该 path 作为展开标记
      path: `/admin/${items[0].path}`,
      title: group,
      iconName: GROUP_ICON[group] || "Document",
      children: items.map((c) => ({
        path: `/admin/${c.path}`,
        title: c.meta.title,
        iconName: c.meta?.icon || "Document",
      })),
    };
  });
};

const sideRoutes = computed(() => {
  const adminRoute = route.matched.find((r) => r.path === "/admin");
  if (!adminRoute || !adminRoute.children) return [];
  return buildSideRoutes(adminRoute.children);
});

// 根据当前路由计算哪些父级菜单应保持展开
const defaultOpeneds = computed(() => {
  return sideRoutes.value
    .filter((g) => g.children.some((c) => route.path === c.path || route.path.startsWith(c.path + "/")))
    .map((g) => g.path);
});

const currentTitle = computed(() => {
  const last = [...route.matched].reverse().find((r) => r.meta?.title);
  return last?.meta?.title || "管理端";
});

const toggleSidebar = () => {
  collapsed.value = !collapsed.value;
};

const handleCommand = async (cmd) => {
  if (cmd === "password") {
    router.push("/admin/password");
    return;
  }
  if (cmd === "theme") {
    themeDialogVisible.value = true;
    return;
  }
  if (cmd === "logout") {
    try {
      await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
        confirmButtonText: "退出",
        cancelButtonText: "取消",
        type: "warning",
      });
      userStore.clear();
      router.push("/login");
    } catch (_) {
      /* canceled */
    }
  }
};
</script>

<style scoped lang="scss">
.admin-layout {
  display: flex;
  width: 100vw;
  height: 100vh;
  background: var(--bg-color-page);

  .admin-sidebar {
    flex-shrink: 0;
    width: 210px;
    height: 100%;
    background: linear-gradient(180deg, #6c7cf3 0%, #5868e6 100%);
    color: #fff;
    display: flex;
    flex-direction: column;
    transition: width 0.2s linear;

    &.collapse {
      width: 64px;
    }

    .logo-bar {
      height: 60px;
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0 16px;
      font-size: 16px;
      font-weight: 600;
      white-space: nowrap;
      overflow: hidden;
    }

    .side-menu {
      flex: 1;
      background: transparent !important;
      border-right: none;
      overflow-y: auto;
      padding: 8px 8px;

      // 父级菜单（子菜单标题）
      :deep(.el-sub-menu__title) {
        color: rgba(255, 255, 255, 0.85) !important;
        border-radius: 4px;

        &:hover {
          background-color: rgba(255, 255, 255, 0.12) !important;
        }
      }

      // 父级菜单激活态：子菜单展开时高亮
      :deep(.el-sub-menu.is-active > .el-sub-menu__title) {
        color: #fff !important;
      }

      // 嵌套子菜单的容器：透明背景、不要内边距
      :deep(.el-sub-menu .el-menu) {
        background: transparent !important;
        padding: 0;
      }

      // 子菜单项
      :deep(.el-menu-item) {
        color: rgba(255, 255, 255, 0.75) !important;
        border-radius: 4px;
        min-width: 0;
        height: 40px;
        line-height: 40px;

        &:hover {
          background-color: rgba(255, 255, 255, 0.12) !important;
        }

        // 被展开父级下的所有子项需要适当缩进
        .el-sub-menu ~ & {
          padding-left: 48px !important;
        }
      }

      :deep(.el-menu-item.is-active) {
        background-color: rgba(255, 255, 255, 0.22) !important;
        color: #fff !important;
      }

      // 折叠时子菜单以弹出层展示时，去掉右侧白色背景
      &.el-menu--collapse :deep(.el-sub-menu .el-menu) {
        background: #5868e6 !important;
      }
    }

    .collapse-btn {
      height: 40px;
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 0 16px;
      cursor: pointer;
      border-top: 1px solid rgba(255, 255, 255, 0.12);
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
      white-space: nowrap;
      overflow: hidden;
    }
  }

  .admin-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .admin-header {
      flex-shrink: 0;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24px;
      background: #fff;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);

      .header-title {
        font-size: 16px;
        font-weight: 600;
      }

      .header-user {
        .user-trigger {
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          font-size: 14px;
          color: #303133;
        }
      }
    }

    .admin-content {
      flex: 1;
      overflow: auto;
      padding: 16px;
    }
  }
}

.theme-dialog {
  padding: 4px 4px 0;

  .theme-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 14px;
  }

  .theme-card {
    border: 2px solid #e8e8e8;
    border-radius: 12px;
    padding: 14px;
    cursor: pointer;
    transition: all 0.25s ease;
    text-align: center;
    background: #fff;

    &:hover {
      border-color: var(--brand-color);
      box-shadow: 0 4px 14px rgba(0, 0, 0, 0.08);
      transform: translateY(-2px);
    }

    &.active {
      border-color: var(--brand-color);
      background: var(--brand-color-light);
      box-shadow: 0 4px 14px rgba(0, 0, 0, 0.08);
    }
  }

  .theme-preview {
    height: 56px;
    border-radius: 8px;
    margin-bottom: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .theme-name {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .theme-desc {
    font-size: 12px;
    color: #999;
    min-height: 18px;
  }
}
</style>