<template>
  <div class="app-layout">
    <!-- 侧边栏 -->
    <AppSidebar
      v-model:collapsed="collapsed"
      :nav-items="visibleModules"
      :active-key="currentModule"
      :user-info="userInfo"
      :role-label="currentRoleLabel"
      @navigate="handleModuleChange"
      @logout="handleLogout"
      @settings="handleSettings"
    />
    
    <!-- 主内容区域 -->
    <main class="main-content">
      <ReadModule 
        v-if="currentModule === 'read'" 
        ref="readModuleRef" 
      />
      <ManageModule 
        v-else-if="currentModule === 'manage'" 
      />
      <QAModule 
        v-else-if="currentModule === 'qa'" 
        ref="qaModuleRef"
      />
      <ExamModule
        v-else-if="currentModule === 'exam'"
        ref="examModuleRef"
      />
      <MindModule 
        v-else-if="currentModule === 'mind'" 
      />
      <DashboardModule 
        v-else-if="currentModule === 'dashboard'" 
      />
      <PermissionModule 
        v-else-if="currentModule === 'permission'" 
        @permissions-updated="handlePermissionsUpdated"
        @refresh-modules="handleRefreshModules"
      />
      <div 
        v-else 
        class="empty-state"
      >
        <a-empty description="暂无权限访问任何功能，请联系管理员分配权限" />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'

// 新增导入 - 侧边栏相关组件和 composable
import { useSidebar } from '../composables/useSidebar'
import AppSidebar from '../components/layout/AppSidebar.vue'

// 模块组件导入
import ReadModule from '../components/ReadModule.vue'
import ManageModule from '../components/ManageModule.vue'
import QAModule from '../components/QAModule.vue'
import ExamModule from '../components/exam/ExamModuleContainer.vue'
import MindModule from '../components/MindModule.vue'
import DashboardModule from '../components/DashboardModule.vue'
import PermissionModule from '../components/PermissionModule.vue'

// 权限管理工具函数
import { 
  getCurrentUserRole,
  getAccessibleModules,
  saveUserRole,
  saveUserPermissions,
  getUserRoleFromStorage,
  getUserPermissionsFromStorage,
  clearUserPermissions,
  moduleNames,
  initUserPermissions,
  initUserPermissionsAfterLogin
} from '../utils/permission.js'

// 事件总线
import { loginStatusChanged, navigateToReaderEvent, navigateToExamWithFileEvent } from '../utils/eventBus.js'

// API 接口
import { authAPI } from '../api/auth.js'

const router = useRouter()
const route = useRoute()

// 使用侧边栏 composable
const {
  collapsed,
  toggleCollapse
} = useSidebar()

const readModuleRef = ref(null)
const examModuleRef = ref(null)

const handleNavigateToReader = (payload) => {
  if (!payload || !payload.filename) return

  if (hasPermission('read')) {
    router.push({
      name: 'Reader',
      query: {
        id: payload.id,
        title: payload.filename,
        extension: payload.extension || '.pdf'
      }
    })
  } else {
    message.warning('您没有文件阅读权限')
  }
}

watch(navigateToReaderEvent, (val) => {
  if (val && val._timestamp) {
    handleNavigateToReader(val)
  }
})

// 监听从文件管理模块传来的出题请求（简化版）
const handleNavigateToExamWithFile = (payload) => {
  if (!payload || !payload.fileData) {
    console.warn('⚠️ [Home] 收到无效的出题请求:', payload)
    return
  }

  console.log('🎯 [Home] 收到出题跳转请求:', payload)

  // 切换到考察训练模块
  if (currentModule.value !== 'exam') {
    if (hasPermission('exam')) {
      currentModule.value = 'exam'
      console.log('✅ [Home] 已切换到考察训练模块')
    } else {
      message.warning('您没有访问考察训练模块的权限')
      return
    }
  }

  // 延迟传递文件信息，确保ExamModule已挂载
  setTimeout(() => {
    if (examModuleRef.value) {
      examModuleRef.value.receiveFileFromReadModule(payload)
      console.log('✅ [Home] 文件信息已传递给ExamModule')
    } else {
      console.warn('⚠️ [Home] ExamModule ref未就绪')
    }
  }, 200)
}

watch(navigateToExamWithFileEvent, (val) => {
  if (val && val._timestamp) {
    handleNavigateToExamWithFile(val)
  }
})

const refreshUserInfo = async () => {
  try {
    console.log('🔍 刷新用户信息...')
    const response = await authAPI.getUserInfo()
    if (response.data.code === 200 && response.data.data) {
      userInfo.value = response.data.data
      localStorage.setItem('userInfo', JSON.stringify(response.data.data))
      console.log('✅ 用户信息已刷新:', response.data.data)
    }
  } catch (error) {
    console.warn('⚠️ 刷新用户信息失败:', error.message)
  }
}

const currentModule = ref('read')
const qaModuleRef = ref(null)
const userRole = ref('')
const userPermissions = ref([])
const accessibleModules = ref([])
const userInfo = ref(null)
const isLoadingRole = ref(false)

// 计算当前角色标签
const currentRoleLabel = computed(() => {
  return userRole.value || '未知角色'
})

// 可见模块列表（用于侧边栏导航）- 使用轻量级线性 SVG 图标
const visibleModules = computed(() => {
  const moduleConfig = [
    { key: 'read', label: '文件查看', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>' },
    { key: 'manage', label: '文件管理', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>' },
    { key: 'qa', label: '知识问答', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>' },
    { key: 'exam', label: '考察训练', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>' },
    { key: 'mind', label: '纲要学习', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>' },
    { key: 'dashboard', label: '综合看板', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>' },
    { key: 'permission', label: '权限管理', icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>' }
  ]
  return moduleConfig.filter(mod => hasPermission(mod.key))
})

// 检查是否有权限访问某个模块
const hasPermission = (module) => {
  const hasAccess = accessibleModules.value && accessibleModules.value.length > 0 && accessibleModules.value.includes(module)

  if (module === 'exam') {
    console.log('🔍 [Home.hasPermission] 详细诊断:')
    console.log('   - accessibleModules 类型:', typeof accessibleModules.value)
    console.log('   - accessibleModules 值:', JSON.stringify(accessibleModules.value))
    console.log('   - accessibleModules 长度:', accessibleModules.value?.length)
    console.log('   - 是否包含 exam:', accessibleModules.value?.includes('exam'))
    console.log('   - 最终结果:', hasAccess ? '✅ 有权限' : '❌ 无权限')
  }

  console.log(`🔍 权限检查 - 模块: "${module}", 结果:`, hasAccess ? '✅ 有权限' : '❌ 无权限', `可访问模块:`, accessibleModules.value)
  return hasAccess
}

// 处理功能模块切换
const handleModuleChange = async (value) => {
  if (value === currentModule.value) {
    return
  }
  
  console.log('🔄 [DEBUG] 准备切换模块:', currentModule.value, '→', value)
  
  // 如果从QA模块切换出去，检查是否有未完成的操作
  if (currentModule.value === 'qa' && qaModuleRef.value) {
    console.log('🔍 [DEBUG] 检查QA模块状态')
    const canLeave = qaModuleRef.value.beforeLeave?.()
    if (canLeave === false) {
      console.log('❌ [DEBUG] 用户取消切换')
      return
    }
    console.log('✅ [DEBUG] 用户确认切换')
  }
  
  if (hasPermission(value)) {
    await refreshUserInfo()
    currentModule.value = value
    console.log('✅ 已切换到模块:', value)
  } else {
    message.warning('您没有权限访问该模块')
    if (!hasPermission(currentModule.value)) {
      const firstAccessible = accessibleModules.value[0]
      if (firstAccessible) {
        currentModule.value = firstAccessible
      }
    }
  }
}

// 处理设置按钮点击（新增方法）
const handleSettings = () => {
  message.info('设置功能开发中...')
}

// 加载用户权限（角色+权限列表）
const loadUserPermissions = async (options = { useCache: true, showLoading: true }) => {
  console.log('📋 开始加载用户权限...')
  console.log('   - 使用缓存:', options.useCache)
  console.log('   - 显示加载状态:', options.showLoading)
  
  if (options.showLoading) {
    isLoadingRole.value = true
  }
  
  try {
    const initResult = await initUserPermissions({ useCache: options.useCache })
    
    if (initResult) {
      userRole.value = initResult.role || ''
      accessibleModules.value = initResult.modules || []
      console.log('✅ 权限加载完成')
      console.log('   - 角色:', userRole.value)
      console.log('   - 可访问模块:', accessibleModules.value)
      console.log('   - 模块数量:', accessibleModules.value.length)
      
      return initResult
    } else {
      console.warn('⚠️ 权限加载返回空结果，确保权限已正确分配')
      accessibleModules.value = []
      return null
    }
    
    if (!hasPermission(currentModule.value)) {
      const firstAccessible = accessibleModules.value[0]
      if (firstAccessible) {
        currentModule.value = firstAccessible
        console.log('🔄 切换到默认模块:', firstAccessible)
      }
    }
  } catch (error) {
    console.error('❌ 加载用户权限失败:', error)
    console.error('   错误详情:', error.message || error)
    
    accessibleModules.value = ['read']
    console.log('🔧 启用安全回退：仅保留 read 模块权限')
    
    throw error
  } finally {
    if (options.showLoading) {
      isLoadingRole.value = false
    }
  }
}

// 处理权限更新（从权限配置页面保存后触发）
const handlePermissionsUpdated = async () => {
  console.log('🔄 收到权限更新事件，开始刷新权限...')
  console.log('   - 当前用户角色:', userRole.value)
  console.log('   - 当前可访问模块:', accessibleModules.value)

  message.info('权限已更新，正在刷新功能栏...')

  try {
    const result = await loadUserPermissions({ useCache: false, showLoading: true })

    if (result && result.modules && result.modules.length > 0) {
      console.log('✅ 权限刷新成功')
      console.log('   - 新的角色:', result.role)
      console.log('   - 新的可访问模块:', result.modules)
      message.success(`功能栏已刷新！当前角色：${result.role}，可访问 ${result.modules.length} 个模块`)

      // 等待下一个 tick，确保所有子组件的 computed 属性都已重新计算
      await nextTick()
      console.log('✅ [Home] 权限刷新完成，子组件应在下一 tick 更新 UI')
    } else {
      console.warn('⚠️ 权限刷新返回空结果')
      message.warning('权限刷新完成，但未获取到可访问模块')
    }
  } catch (error) {
    console.error('❌ 权限刷新失败:', error)
    message.error('权限刷新失败，请尝试重新登录')

    if (!accessibleModules.value || accessibleModules.value.length === 0) {
      console.log('🔧 启用回退方案：提供最小权限（read模块）')
      accessibleModules.value = ['read']
      if (!hasPermission(currentModule.value)) {
        currentModule.value = 'read'
      }
      message.warning('已启用安全模式，仅可访问基础功能')
    }
  }
}

// 处理刷新模块（从权限配置页面切换时触发，静默刷新）
const handleRefreshModules = async () => {
  await loadUserPermissions({ useCache: true, showLoading: false })
}

// 处理退出登录
const handleLogout = async () => {
  localStorage.removeItem('token')
  localStorage.removeItem('refreshToken')
  localStorage.removeItem('userInfo')
  localStorage.removeItem('isLoggedIn')
  clearUserPermissions()
  message.success('已退出登录')
  window.location.href = '/'
}

// 初始化时加载权限
onMounted(async () => {
  console.log('===== Home 组件挂载，开始初始化 =====')
  
  accessibleModules.value = []
  console.log('📝 已清空模块列表，等待权限加载完成...')

  try {
    const initResult = await initUserPermissions({ useCache: false })

    if (initResult) {
      userRole.value = initResult.role || ''
      accessibleModules.value = [...(initResult.modules || [])]
      console.log('✅ 权限加载完成 - 角色:', userRole.value, '模块:', accessibleModules.value)

      if (!hasPermission(currentModule.value)) {
        const firstAccessible = accessibleModules.value[0]
        if (firstAccessible) {
          currentModule.value = firstAccessible
          console.log('🔄 切换到默认模块:', firstAccessible)
        }
      }
      
      await refreshUserInfo()

      // 处理从文件阅读器返回（恢复 AI 对话会话）
      // 方式1: 通过URL参数（兼容旧逻辑）
      const returnModule = route.query.module
      const returnSid = route.query.sid
      
      // 方式2: 通过sessionStorage（新的浏览器后退支持）
      let readerReturnInfo = null
      try {
        const savedInfo = sessionStorage.getItem('qa_return_from_reader')
        if (savedInfo) {
          readerReturnInfo = JSON.parse(savedInfo)
          // 立即清除，避免重复使用
          sessionStorage.removeItem('qa_return_from_reader')
          console.log('[HOME] 🔄 检测到从阅读器返回（sessionStorage）:', readerReturnInfo)
        }
      } catch (e) {
        console.warn('[HOME] 读取阅读器返回信息失败:', e)
      }

      // 判断是否需要恢复QA模块
      const shouldRestoreQA = (returnModule === 'qa') || 
                              (readerReturnInfo && readerReturnInfo.from === 'reader')
      
      if (shouldRestoreQA && hasPermission('qa')) {
        currentModule.value = 'qa'
        console.log('📋 从阅读器返回，切换到知识问答模块', { returnModule, readerReturnInfo })
        
        await nextTick()
        
        // 优先使用sessionStorage中的sid，其次使用query参数
        const sidToRestore = readerReturnInfo?.sid || returnSid
        
        if (sidToRestore && qaModuleRef.value) {
          setTimeout(() => {
            qaModuleRef.value.restoreSession(sidToRestore)
            console.log('📋 恢复会话:', sidToRestore)
          }, 500)
        }
        
        // 只清理query参数，不清除可能还有的其他参数
        if (returnModule) {
          router.replace({ 
            query: { ...route.query, module: undefined, sid: undefined } 
          })
        }
      }
    } else {
      console.warn('⚠️ 权限初始化返回空，确保权限已正确分配')
      accessibleModules.value = []
    }
  } catch (error) {
    console.error('❌ 初始化权限失败:', error)
    accessibleModules.value = []
  }
})
</script>

<style scoped>
.app-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  flex: 1;
  min-width: 0;
  overflow: auto;
  background: var(--bg-page);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 移动端适配 */
@media (max-width: 767px) {
  .main-content {
    width: 100%;
  }
}
</style>
