<template>
    <div class="main-container" :class="themeClass">
        <!-- 左侧菜单栏组件 - 添加主题类传递 -->
        <div class="menu-view" :class="{ collapsed: isSidebarCollapsed }">
            <MainMenu 
                :collapsed="isSidebarCollapsed"
                @toggle="isSidebarCollapsed = !isSidebarCollapsed"
                @menu-click="handleMenuChange"
                :theme-class="themeClass"  
            />
        </div>
        <!-- 右侧主内容区 -->
        <div class="right-view">
            <div class="top-view">
                <!-- 主题和语言切换控件 -->
                <div class="header-controls">
                    <!-- 语言切换 -->
                    <el-select 
                        v-model="currentLanguage" 
                        size="small" 
                        class="language-select"
                        @change="handleLanguageChange"
                    >
                        <el-option label="中文" value="zh-CN"></el-option>
                        <el-option label="English" value="en-US"></el-option>
                    </el-select>
                    
                    <!-- 主题切换 -->
                    <el-select 
                        v-model="currentTheme" 
                        size="small"
                        class="theme-select"
                        @change="handleThemeChange"
                    >
                        <el-option :label="t('theme.light')" value="light"></el-option>
                        <el-option :label="t('theme.dark')" value="dark"></el-option>
                        <el-option :label="t('theme.custom')" value="custom"></el-option>
                    </el-select>
                </div>
                
                <!-- 顶部用户信息栏组件 -->
                <UserInfoBar 
                    :user-info="currentUser"
                    :unread-count="unreadNotifications"
                    @logout="handleLogout"
                    @notification-click="handleNotificationClick"
                    @settings-click="handleSettingsClick"
                />
            </div>
            <div class="connect-view">
                <!-- 路由视图放在右侧内容区 -->
                <RouterView />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, inject, watch, nextTick } from 'vue';  // 增加nextTick用于强制刷新
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElNotification } from 'element-plus';
import Cookies from 'js-cookie';
import crypto from '@/utils/crypto';
import MainMenu from './layout/MainMenu.vue';
import UserInfoBar from './layout/UserInfoBar.vue';
import { getLocale, setLocale } from '@/utils/storage';

// 注入主题配置
const theme = inject('theme', { 
  currentTheme: 'light',
  switchTheme: () => {}
});

// 国际化
const { locale, t } = useI18n();

// 退出登录函数
const logout = async () => {
  try {
    localStorage.removeItem('userInfo');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('user_gid');
    Cookies.remove('access_token');
    
    await router.push('/auth');
    window.location.reload();
    return Promise.resolve();
  } catch (error) {
    console.error('退出登录失败:', error);
    return Promise.reject(error);
  }
};

// 状态管理
const isSidebarCollapsed = ref(false);
const unreadNotifications = ref(3);
const currentUser = ref({
  name: t('user.unknown'),
  role: t('user.unauthorized'),
  avatar: 'https://picsum.photos/id/64/200/200',
  userId: '',
  departmentId: ''
});

// 主题和语言状态
const currentTheme = ref(theme.currentTheme);
const currentLanguage = ref(getLocale() || 'zh-CN');
const themeClass = ref(`theme-${currentTheme.value}`);

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

// 从localStorage获取并解密用户信息
const loadUserInfo = () => {
  try {
    const encryptedUserInfo = localStorage.getItem('userInfo');
    
    if (!encryptedUserInfo) {
      throw new Error(t('error.noUserInfo'));
    }
    
    if (!/^[A-Za-z0-9+/=]+$/.test(encryptedUserInfo)) {
      throw new Error(t('error.invalidBase64'));
    }
    
    const decryptedInfo = crypto.decrypt(encryptedUserInfo);
    
    if (!decryptedInfo || decryptedInfo === '') {
      throw new Error(t('error.decryptFailed'));
    }
    
    let userData;
    try {
      userData = JSON.parse(decryptedInfo);
    } catch (jsonError) {
      throw new Error(`${t('error.jsonParseFailed')}: ${jsonError.message}`);
    }
    
    if (typeof userData !== 'object' || userData === null) {
      throw new Error(t('error.invalidUserInfo'));
    }
    
    const userName = userData.userName || userData.loginName || t('user.unknown');
    const roles = Array.isArray(userData.roles) ? userData.roles : [];
    const role = roles.length > 0 ? roles[0] : t('user.defaultRole');
    
    if (userData.userGid) {
      localStorage.setItem('user_gid', userData.userGid);
    } else if (userData.groupId) {
      localStorage.setItem('user_gid', userData.groupId);
    }
    
    return {
      name: userName,
      role: role,
      avatar: 'https://picsum.photos/id/64/200/200',
      userId: userData.userId || '',
      departmentId: userData.departmentId || '',
      loginName: userData.loginName || '',
      loginTime: userData.loginTime || ''
    };
  } catch (error) {
    console.error('加载用户信息失败详情:', error);
    localStorage.removeItem('userInfo');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('user_gid');
    throw error;
  }
};

// 初始化
onMounted(async () => {
  try {
    locale.value = currentLanguage.value;
    
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    const hasToken = !!Cookies.get('access_token');
    
    if (!isLoggedIn || !hasToken) {
      ElMessage.warning(t('auth.sessionExpired'));
      await router.push('/auth');
      return;
    }
    
    const userData = loadUserInfo();
    currentUser.value = userData;
    
    ElNotification.success({
      title: t('auth.loginSuccess'),
      message: `${t('auth.welcomeBack')}，${userData.name}`,
      duration: 3000
    });
  } catch (error) {
    ElMessage.error(`${t('error.loadUserFailed')}: ${error.message}`);
    console.error('初始化用户信息时出错:', error);
    
    setTimeout(() => {
      router.push('/auth');
    }, 2000);
  }
});

// 处理主题切换 - 增加强制刷新逻辑
const handleThemeChange = async (newTheme) => {
  if (theme.switchTheme) {
    theme.switchTheme(newTheme);
    currentTheme.value = newTheme;
    themeClass.value = `theme-${newTheme}`;
    
    // 强制DOM更新，确保所有子组件感知主题变化
    await nextTick();
    // 触发重绘技巧：短暂移除再添加主题类
    const tempClass = themeClass.value;
    themeClass.value = '';
    await nextTick();
    themeClass.value = tempClass;
    
    ElMessage.success(t('theme.themeSwitched', { theme: newTheme }));
  }
};

// 处理语言切换
const handleLanguageChange = (newLocale) => {
  locale.value = newLocale;
  setLocale(newLocale);
  currentLanguage.value = newLocale;
  ElMessage.success(t('common.languageChanged'));
  
  if (!currentUser.value.name || currentUser.value.name === '未知用户') {
    currentUser.value.name = t('user.unknown');
  }
  if (!currentUser.value.role || currentUser.value.role === '未授权') {
    currentUser.value.role = t('user.unauthorized');
  }
};

// 处理菜单切换
const handleMenuChange = (path) => {
  if (path && path !== router.currentRoute.value.path) {
    router.push(path);
  }
};

// 处理退出登录
const handleLogout = async () => {
  try {
    await logout();
    ElMessage.success(t('auth.logoutSuccess'));
  } catch (error) {
    ElMessage.error(t('auth.logoutFailed'));
  }
};

// 处理通知点击
const handleNotificationClick = () => {
  ElMessage.info(t('notification.openCenter'));
};

// 处理设置点击
const handleSettingsClick = () => {
  router.push('/profile');
};

// 监听主题变化 - 确保菜单同步更新
watch(
  () => theme.currentTheme,
  async (newTheme) => {
    currentTheme.value = newTheme;
    themeClass.value = `theme-${newTheme}`;
    // 主题变化时强制菜单重绘
    await nextTick();
    const menuEl = document.querySelector('.menu-view');
    if (menuEl) {
      menuEl.style.display = 'none';
      await nextTick();
      menuEl.style.display = 'block';
    }
  }
);
</script>

<style scoped>
.main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  overflow: hidden;
  background-color: var(--color-background);
  color: var(--color-text);
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* 关键修复：确保主题类能影响菜单内部样式 */
.menu-view {
  width: 200px;
  height: 100%;
  border-right: 1px solid var(--color-border);
  flex-shrink: 0;
  transition: width 0.3s ease;
  background-color: var(--color-surface);
}

/* 穿透到子组件的菜单样式 - 解决scoped隔离问题 */
:deep(.menu-view) {
  --menu-bg-color: var(--color-surface);
  --menu-text-color: var(--color-text);
  --menu-hover-color: var(--color-surface-alt);
  --menu-active-color: var(--color-primary);
}

.menu-view.collapsed {
  width: 60px;
}

.right-view {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.top-view {
  height: 60px;
  border-bottom: 1px solid var(--color-border);
  display: flex;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;
  background-color: var(--color-surface);
  justify-content: space-between;
}

.header-controls {
  display: flex;
  gap: 12px;
}

.language-select, .theme-select {
  width: 110px;
  /* 确保选择器本身也响应主题 */
  :deep(.el-input__inner) {
    background-color: var(--color-surface-alt) !important;
    border-color: var(--color-border) !important;
    color: var(--color-text) !important;
  }
  :deep(.el-select-dropdown) {
    background-color: var(--color-surface) !important;
    border-color: var(--color-border) !important;
    :deep(.el-select-dropdown__item) {
      color: var(--color-text) !important;
      &:hover {
        background-color: var(--color-surface-alt) !important;
      }
      &.selected {
        color: var(--color-primary) !important;
        background-color: var(--color-surface-alt) !important;
      }
    }
  }
}

.connect-view {
  flex: 1;
  overflow: auto;
  width: 100%;
  padding: 0;
  margin: 0;
  background-color: var(--color-background);
  border: none;
  box-sizing: border-box;
}
</style>
    