<template>
  <div class="app-container">
    <a-layout style="min-height: 100vh;">
      <!-- 顶部导航栏 -->
      <a-layout-header class="header">
        <div class="logo">
          <img src="/my.png" class="logo-img" alt="系统Logo" />
          <span class="system-name">cApi</span>
        </div>
        <div class="header-actions">
          <div class="search-box">
            <!-- 直接使用全局注册的图标 -->
            <SearchOutlined class="search-icon" />
            <input type="text" placeholder="搜索" class="search-input" />
          </div>
          <div class="action-icons">
            <a-tooltip title="收藏">
              <StarOutlined class="action-icon" @click="showFavorite = true" />
            </a-tooltip>
            <a-tooltip title="通知">
              <BellOutlined class="action-icon" @click="showNotification = true" />
            </a-tooltip>
            <a-tooltip title="帮助">
              <QuestionCircleOutlined class="action-icon" @click="showHelp = true" />
            </a-tooltip>
            <a-tooltip title="设置">
              <SettingOutlined class="action-icon" @click="showSettings = true" />
            </a-tooltip>
          </div>
          <a-dropdown
            placement="bottomRight"
            :auto-adjust-overflow="true"
            @visible-change="handleDropdownVisible"
          >
            <div class="user-avatar">
              <img src="https://picsum.photos/id/1005/200/200" alt="用户头像" class="avatar-img" />
            </div>
            <template #overlay>
              <a-menu class="user-menu" @click="handleUserMenuClick">
                <a-menu-item key=""> <img src="https://picsum.photos/id/1005/200/200" alt="用户头像" class="avatar-img" />{{userName}}</a-menu-item>
				<a-menu-divider />
                <a-menu-item key="profile">
				  <UserOutlined class="mr-2" />	个人资料
				</a-menu-item>
                <a-menu-item key="settings">
				 <ToolFilled class="mr-2" /> 修改密码
				</a-menu-item>
                <a-menu-divider />
                <a-menu-item key="logout" class="logout-menu-item">
                  <!-- 直接使用全局注册的图标 -->
                  <LogoutOutlined class="mr-2" /> 退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>

      <!-- 中间主体布局 -->
      <a-layout style="flex: 1; height: calc(100vh - 64px);">
        <!-- 左侧菜单 -->
        <a-layout-sider 
          class="side-menu-container" 
          width="200" 
          :collapsed="collapsed" 
          :trigger="null"
          collapsible
          :class="{ 'sider-collapsed': collapsed }"
        >
          <div v-if="loading" class="menu-loading"><a-spin size="large" /></div>
          <div v-else class="menu-scroll-container">
            <div 
              v-for="(module, moduleKey) in moduleMenusConfig" 
              :key="module.moduleCode"
              class="parent-menu-item"
            >
              <!-- 折叠状态：悬浮子菜单 -->
              <a-dropdown
                v-if="collapsed"
                placement="right"
                :auto-adjust-overflow="true"
                :open="collapsedMenuVisible[module.moduleCode]"
                @openChange="(visible) => handleCollapsedMenuVisible(visible, module.moduleCode)"
              >
                <div class="parent-menu-header collapsed-mode" @click.stop>
                  <!-- 动态图标：通过封装的图标库获取 -->
                  <component :is="getIconComponent(module.icon)" class="parent-menu-icon" />
                  <a-tooltip :title="module.moduleName" placement="right">
                    <span class="collapsed-tooltip-placeholder" />
                  </a-tooltip>
                </div>
                <template #overlay>
                  <a-menu 
                    class="collapsed-sub-menu"
                    @click="(e) => handleCollapsedSubMenuClick(e, module.menus)"
                  >
                    <a-menu-item
                      v-for="menu in module.menus"
                      :key="menu.menuCode"
                      :selected="selectedKey === menu.menuCode"
                      :disabled="!menu.chref"
                    >
                      <component :is="getIconComponent(menu.cicon)" class="sub-menu-icon" />
                      <span>{{ menu.menuName }}</span>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>

              <!-- 展开状态：点击展开子菜单 -->
              <div v-else>
                <div 
                  class="parent-menu-header"
                  @click="toggleSubMenu(module.moduleCode)"
                >
                  <component :is="getIconComponent(module.icon)" class="parent-menu-icon" />
                  <span class="parent-menu-title">{{ module.moduleName }}</span>
                  <!-- 动态图标：直接使用全局注册的图标（无需映射） -->
                  <component 
                    :is="isSubMenuOpen(module.moduleCode) ? 'CaretUpOutlined' : 'CaretDownOutlined'" 
                    class="parent-menu-caret"
                  />
                </div>
                <div 
                  class="sub-menu-list"
                  :class="{ 'sub-menu-visible': isSubMenuOpen(module.moduleCode) }"
                >
                  <div
                    v-for="menu in module.menus"
                    :key="menu.menuCode"
                    class="sub-menu-item"
                    :class="{ 
                      'sub-menu-item-active': selectedKey === menu.menuCode,
                      'sub-menu-item-disabled': !menu.chref
                    }"
                    @click="handleSubMenuItemClick(menu)"
                    :style="{ cursor: menu.chref ? 'pointer' : 'not-allowed' }"
                  >
                    <component :is="getIconComponent(menu.cicon)" class="sub-menu-icon" />
                    <span>{{ menu.menuName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="collapse-trigger" @click="collapsed = !collapsed">
            <!-- 直接使用全局注册的图标 -->
            <component :is="collapsed ? 'MenuUnfoldOutlined' : 'MenuFoldOutlined'" />
          </div>
        </a-layout-sider>

        <!-- 右侧内容区 -->
        <a-layout-content class="right-content">
          <!-- 标签页 -->
          <div class="tab-bar">
            <a-tag
              :class="['console-tab', $route.path === '/index/console' ? 'console-tab--active' : '']"
              @click="switchToConsole"
            >
              <!-- 直接使用全局注册的图标 -->
              <HomeOutlined class="console-tab-icon" />
              <span>控制台</span>
            </a-tag>
            <a-button
              size="small"
              class="tab-nav-btn"
              @click="switchTab('prev')"
              :disabled="currentTabIndex === 0 || otherTabs.length === 0"
              ghost
            >
              &lt;
            </a-button>
            <a-tabs
              v-model:activeKey="activeTabKey"
              @change="handleTabChange"
              class="google-tabs"
              :animated="false"
              hide-add
            >
              <a-tab-pane
                v-for="tab in otherTabs"
                :key="tab.key"
                :tab="renderTabTitle(tab)"
              />
            </a-tabs>
            <a-button
              size="small"
              class="tab-nav-btn"
              @click="switchTab('next')"
              :disabled="currentTabIndex === otherTabs.length - 1 || otherTabs.length === 0"
              ghost
            >
              &gt;
            </a-button>
            <a-button
              size="small"
              class="close-all-btn"
              @click="closeAllTabs"
              :disabled="otherTabs.length === 0"
              ghost
            >
              <!-- 直接使用全局注册的图标 -->
              <CloseOutlined class="close-icon" /> 关闭所有
            </a-button>
          </div>

          <!-- 内容区核心：Suspense + RouterView -->
          <a-layout-content class="main-content">
            <div class="home-content">
              <Suspense>
                <template #default>
                  <RouterView @error="handleRouterViewError" />
                </template>
                <template #fallback>
                  <div class="content-loading">
                    <a-spin size="large" tip="页面加载中..." />
                  </div>
                </template>
              </Suspense>

              <div v-if="componentError" class="component-error">
                <!-- 直接使用全局注册的图标 -->
                <ExclamationCircleOutlined class="error-icon" />
                <p class="error-title">组件加载失败</p>
                <p class="error-desc">请检查路由配置或页面文件是否存在</p>
                <p class="error-path">失败路由：{{ errorPath }}</p>
                <a-button 
                  type="primary" 
                  size="middle" 
                  class="retry-btn"
                  @click="reloadCurrentRoute"
                >
                  重新加载
                </a-button>
              </div>
            </div>
          </a-layout-content>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- 退出确认对话框 -->
    <a-modal
      v-model:open="logoutVisible"
      :centered="true"
      :closable="false"
      :mask-closable="false"
      :footer="null"
      :width="420"
      wrap-class-name="logout-modal-wrapper"
    >
      <div class="logout-body">
        <p class="logout-title">
          <ExclamationCircleOutlined style="color:#faad14; margin-right:8px;" />
          温馨提示
        </p>
        <p class="logout-desc">是否确认退出系统？</p>
        <div class="logout-actions">
          <a-button size="large" @click="logoutVisible = false">取消</a-button>
          <a-button type="primary" size="large" style="margin-left: 16px" @click="doLogout">确定</a-button>
        </div>
      </div>
    </a-modal>
  </div>
  
  <!-- 放在根节点最下方即可 -->
  <Favorite v-if="showFavorite" :visible="showFavorite" @close="showFavorite = false" />
  <Notification v-if="showNotification" :visible="showNotification" @close="showNotification = false" />
  <Help v-if="showHelp" :visible="showHelp" @close="showHelp = false" />
  <Settings v-if="showSettings" :visible="showSettings" @close="showSettings = false" />
  
  <!-- 个人资料 -->
  <UserProfile v-if="showUserProfile" :visible="showUserProfile" @close="showUserProfile = false" />
  <!-- 修改密码 -->
  <ChangePwd   v-if="showChangePwd"   :visible="showChangePwd"   @close="showChangePwd = false" />
</template>

<script setup lang="ts">
import { ref, computed, h, reactive, watch, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute, RouterView, RouteLocationNormalized } from 'vue-router';
import { Layout, Menu, Button, Tabs, Tag, Dropdown, Modal, Tooltip, Spin, message } from 'ant-design-vue';
import { getModuleMenus, ModuleItem, MenuItem } from '@/api/menu';
import { getUserName } from '@/utils/user';
import { apiLogout } from '@/api/auth'

// 关键修改1：导入封装的图标库（全局注册的基础，动态图标从这里获取）
import icons from '@/icons'; 
import type { AntdIcon } from '@/icons'; // 导入图标类型，确保TypeScript提示

// 路由实例
const router = useRouter();
const route = useRoute();

const userName = computed(() => getUserName());

// 登录态校验守卫
const removeAuthGuard = router.beforeEach((to, from, next) => {
  const userInfo = localStorage.getItem('userInfo');
  // 未登录且访问非登录页时跳转登录
  if (to.path !== '/login' && !userInfo) {
    next('/login');
  } else {
    next();
  }
});

// 状态管理
const collapsed = ref(false);
const logoutVisible = ref(false);
const selectedKey = ref('');
const expandedParentMenus = ref<string[]>([]);
const loading = ref(true);
const componentError = ref(false);
const errorPath = ref('');
const isNavigating = ref(false);

const showFavorite     = ref(false)
const showNotification = ref(false)
const showHelp         = ref(false)
const showSettings     = ref(false)
const showUserProfile  = ref(false);
const showChangePwd    = ref(false);

// 菜单配置
const moduleMenusConfig = ref<ModuleItem[]>([]);
const collapsedMenuVisible = reactive<Record<string, boolean>>({});

// 标签页数据结构（初始路径为/index/console）
interface TabItem {
  key: string;
  title: string;
  path: string; // 统一为/index/xxx格式
  closable: boolean;
}
const allTabs = ref<TabItem[]>([
  { key: 'console', title: '控制台', path: '/index/console', closable: false }
]);

// 计算属性
const otherTabs = computed(() => allTabs.value.filter(tab => tab.key !== 'console'));
const activeTabKey = computed({
  get() {
    const matchedTab = allTabs.value.find(tab => tab.path === route.path);
    return matchedTab ? matchedTab.key : 'console';
  },
  set(key) {
    const matchedTab = allTabs.value.find(tab => tab.key === key);
    if (matchedTab && !isNavigating.value) {
      navigateToPath(matchedTab.path);
    }
  }
});
const currentTabIndex = computed(() => {
  return otherTabs.value.findIndex(tab => tab.path === route.path);
});

// 菜单数据加载（标准化chref为/index/xxx）
const fetchMenuData = async () => {
  try {
    loading.value = true;
    const modules = await getModuleMenus();
    // 标准化菜单路径：确保为/index/xxx格式
    const normalizedModules = modules.map(module => ({
      ...module,
      menus: module.menus.map(menu => ({
        ...menu,
        chref: menu.chref 
          ? menu.chref.startsWith('/index') 
            ? menu.chref 
            : `/index${menu.chref.startsWith('/') ? menu.chref : `/${menu.chref}`}`
          : ''
      }))
    }));
    moduleMenusConfig.value = normalizedModules;
    normalizedModules.forEach(module => collapsedMenuVisible[module.moduleCode] = false);
    syncMenuStateWithRoute(route);
  } catch (error) {
    console.error('菜单接口请求失败:', error);
    Modal.error({ title: '菜单加载失败', content: '请刷新页面重试' });
  } finally {
    loading.value = false;
  }
};

// 路由跳转封装
const navigateToPath = async (path: string) => {
  if (isNavigating.value || path === route.path) return;
  try {
    isNavigating.value = true;
    await router.push(path);
  } catch (err) {
    console.error('路由跳转失败:', err);
    Modal.error({ title: '页面跳转失败', content: `目标路径不存在：${path}` });
  } finally {
    isNavigating.value = false;
  }
};

// 同步菜单与路由状态
const syncMenuStateWithRoute = (currentRoute: RouteLocationNormalized) => {
  // 匹配控制台路径/index/console
  if (currentRoute.path === '/index/console') {
    selectedKey.value = '';
    expandedParentMenus.value = [];
    return;
  }

  // 匹配其他菜单路由
  let matched = false;
  for (const module of moduleMenusConfig.value) {
    const menu = module.menus.find(item => item.chref === currentRoute.path);
    if (menu) {
      selectedKey.value = menu.menuCode;
      expandedParentMenus.value = [module.moduleCode];
      matched = true;
      break;
    }
  }

  // 未匹配时跳回控制台
  if (!matched && currentRoute.path !== '/index/console') {
    navigateToPath('/index/console');
  }
};

// 关键修改2：重写getIconComponent，从封装的图标库获取图标（不再依赖局部导入）
const getIconComponent = (iconName: string) => {
  // 图标名称格式校验（确保是有效的Antd图标名称，如"ApiOutlined"）
  const validIconName = iconName as AntdIcon;
  // 从封装的图标库中获取，不存在则返回默认图标（ApiOutlined）
  return icons[validIconName] || icons.ApiOutlined;
};

// 检查父菜单是否展开
const isSubMenuOpen = (moduleCode: string) => {
  return expandedParentMenus.value.includes(moduleCode);
};

// 菜单交互
const toggleSubMenu = (moduleCode: string) => {
  expandedParentMenus.value = isSubMenuOpen(moduleCode) ? [] : [moduleCode];
};

const handleCollapsedMenuVisible = (visible: boolean, moduleCode: string) => {
  Object.keys(collapsedMenuVisible).forEach(key => {
    if (key !== moduleCode) collapsedMenuVisible[key] = false;
  });
  collapsedMenuVisible[moduleCode] = visible;
};

const handleSubMenuItemClick = (menu: MenuItem) => {
  if (!menu.chref) return;
  navigateToPath(menu.chref);
  
  // 添加标签页
  const tabExists = allTabs.value.some(tab => tab.path === menu.chref);
  if (!tabExists) {
    allTabs.value.push({
      key: menu.menuCode,
      title: menu.menuName,
      path: menu.chref,
      closable: true
    });
  }
  
  Object.keys(collapsedMenuVisible).forEach(key => collapsedMenuVisible[key] = false);
};

const handleCollapsedSubMenuClick = (e: { key: string }, menus: MenuItem[]) => {
  const menuCode = e.key;
  const menu = menus.find(item => item.menuCode === menuCode);
  if (menu) handleSubMenuItemClick(menu);
};

// 标签页交互
const renderTabTitle = (tab: TabItem) => {
  return h('div', { class: 'tab-title-container' }, [
    h('span', { class: 'tab-title-text' }, tab.title),
    tab.closable && h(
      'span',
      {
        class: 'tab-close-btn',
        onClick: (e: Event) => { 
          e.stopPropagation(); 
          deleteTab(tab); 
        }
      },
      // 关键修改：用 getIconComponent 获取 CloseOutlined 图标
      h(getIconComponent('CloseOutlined'), { size: 12 })
    )
  ]);
};

const switchToConsole = () => {
  navigateToPath('/index/console');
  Object.keys(collapsedMenuVisible).forEach(key => collapsedMenuVisible[key] = false);
};

const switchTab = (direction: 'prev' | 'next') => {
  const tabs = otherTabs.value;
  if (tabs.length === 0) return;

  const currentIdx = currentTabIndex.value;
  let targetIdx = direction === 'prev' ? currentIdx - 1 : currentIdx + 1;
  targetIdx = Math.max(0, Math.min(targetIdx, tabs.length - 1));
  
  navigateToPath(tabs[targetIdx].path);
};

const deleteTab = (tab: TabItem) => {
  if (!tab.closable) return;

  const tabIndex = allTabs.value.findIndex(item => item.key === tab.key);
  if (tabIndex === -1) return;

  const isActive = tab.path === route.path;
  allTabs.value = allTabs.value.filter(item => item.key !== tab.key);

  if (isActive) {
    const tabs = otherTabs.value;
    if (tabs.length > 0) {
      const targetTab = tabs[tabIndex - 1] || tabs[tabIndex];
      navigateToPath(targetTab.path);
    } else {
      navigateToPath('/index/console');
    }
  }
};

const closeAllTabs = () => {
  allTabs.value = allTabs.value.filter(tab => tab.key === 'console');
  navigateToPath('/index/console');
  Object.keys(collapsedMenuVisible).forEach(key => collapsedMenuVisible[key] = false);
};

const handleTabChange = (key: string) => {
  const matchedTab = allTabs.value.find(tab => tab.key === key);
  if (matchedTab) navigateToPath(matchedTab.path);
};

// 错误处理
const handleRouterViewError = (err: Error) => {
  componentError.value = true;
  errorPath.value = route.path;
  console.error('路由组件加载失败:', err);
};

const reloadCurrentRoute = () => {
  componentError.value = false;
  router.replace({
    path: route.path,
    query: { ...route.query, t: Date.now() }
  });
};

// 用户菜单与退出登录
const handleDropdownVisible = (visible: boolean) => {
  console.log('用户下拉菜单状态：', visible ? '显示' : '隐藏');
};

const handleUserMenuClick = ({ key }: { key: string }) => {
  switch (key) {
    case 'profile':
      showUserProfile.value = true;
      break;
    case 'settings':
      showChangePwd.value = true;
      break;
    case 'logout':
      handleLogout();
      break;
    default:
      console.log('用户菜单点击：', key);
  }
};

const handleLogout = () => {
  logoutVisible.value = true;
};


const doLogout = async () => {
  try {
    // 1. 调用后端登出接口（可选）
    const response = await apiLogout();
	if (response.code == 200 ){
		// 2. 清掉所有缓存
	   localStorage.clear();
	   sessionStorage.clear();
	   logoutVisible.value = false;
	   window.location.href = `${import.meta.env.BASE_URL}login`;
	}
  } catch (e) {
	message.error('退出失败，请重试');
  }
};

// 生命周期
onMounted(() => {
  fetchMenuData();
  router.afterEach((to) => {
    componentError.value = false;
    syncMenuStateWithRoute(to);
  });
});

onUnmounted(() => {
  removeAuthGuard();
});

watch(collapsed, (newVal) => {
  if (newVal) expandedParentMenus.value = [];
  else syncMenuStateWithRoute(route);
});
</script>

<style scoped>
@import "styles/app-layout.css";

.main-content {
  padding: 16px;
  height: calc(100% - 48px);
  overflow: auto;
  background: #f5f7fa;
}

.content-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 12px;
}

.component-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #f5222d;
  gap: 16px;
  padding: 24px;
  text-align: center;
}

.error-icon {
  font-size: 48px;
}

.error-title {
  font-size: 18px;
  font-weight: 500;
}

.error-desc, .error-path {
  font-size: 14px;
  color: #666;
}

.retry-btn {
  margin-top: 8px;
}

.sub-menu-item-disabled {
  color: #ccc !important;
  background: transparent !important;
}
</style>