<template>
  <div class="exam-module-container">
    <TabsBar
      :tabs="moduleTabs"
      v-model="activeModule"
    />

    <div v-show="isCurrentPanelAccessible" class="panel-wrapper">
      <component
        :is="currentPanelComponent"
        :preselected-file="pendingFileForGeneratePanel"
        @panel-event="handlePanelEvent"
        ref="panelRef"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import TabsBar from '../common/TabsBar.vue'
import GeneratePanel from './GeneratePanel.vue'
import QuestionBankPanel from './QuestionBankPanel.vue'
import PaperManagementPanel from './PaperManagementPanel.vue'
import TrainingPanel from './TrainingPanel.vue'
import ExamPanel from './ExamPanel.vue'
import { getDirectPermission } from '../../utils/permission.js'

const activeModule = ref('generate')
const panelRef = ref(null)

// 存储从文件管理模块传来的文件信息（使用简单的ref）
const pendingFileForGeneratePanel = ref(null)

const canShowGenerate = computed(() => getDirectPermission('exam:ai'))
const canShowBank = computed(() => getDirectPermission('exam:bank'))
const canShowPaper = computed(() => getDirectPermission('exam:paper'))
const canShowTrain = computed(() => getDirectPermission('exam:train'))
const canShowExam = computed(() => getDirectPermission('exam:exam'))

const moduleTabs = computed(() => {
  const tabs = []
  if (canShowGenerate.value) tabs.push({ key: 'generate', label: 'AI智能出题', icon: 'robot' })
  if (canShowBank.value) tabs.push({ key: 'bank', label: '题库管理', icon: 'clipboard' })
  if (canShowPaper.value) tabs.push({ key: 'paper', label: '智能组卷', icon: 'target' })
  if (canShowTrain.value) tabs.push({ key: 'train', label: '互动训练', icon: 'edit' })
  if (canShowExam.value) tabs.push({ key: 'exam', label: '试卷考核', icon: 'file-text' })
  return tabs
})

// 如果当前 tab 无权限访问则自动切换到第一个有权限的 tab
const isCurrentPanelAccessible = computed(() => {
  const tabKeys = moduleTabs.value.map(t => t.key)
  return tabKeys.includes(activeModule.value)
})

// 监听 moduleTabs 变化，自动切换无权限的 tab
watch(moduleTabs, (tabs) => {
  const tabKeys = tabs.map(t => t.key)
  if (tabKeys.length > 0 && !tabKeys.includes(activeModule.value)) {
    activeModule.value = tabKeys[0]
  }
}, { immediate: true })

const panelComponents = {
  generate: GeneratePanel,
  bank: QuestionBankPanel,
  paper: PaperManagementPanel,
  train: TrainingPanel,
  exam: ExamPanel
}

const currentPanelComponent = computed(() => panelComponents[activeModule.value])

const handlePanelEvent = (event) => {
  console.log('Panel event:', event)
}

/**
 * 接收从文件管理模块(ReadModule)传来的文件信息
 * 由Home.vue调用此方法
 */
const receiveFileFromReadModule = (payload) => {
  console.log('📥 [ExamModuleContainer] 接收到文件信息:', payload)

  if (!payload || !payload.fileData) {
    console.warn('⚠️ [ExamModuleContainer] 收到无效的文件信息')
    return
  }

  // 存储文件信息（响应式更新会触发GeneratePanel的watch）
  pendingFileForGeneratePanel.value = payload

  // 切换到AI智能出题标签页
  if (canShowGenerate.value) {
    activeModule.value = 'generate'
  } else if (moduleTabs.value.length > 0) {
    activeModule.value = moduleTabs.value[0].key
  }

  console.log('✅ [ExamModuleContainer] 文件信息已设置，等待GeneratePanel处理')
}

// 暴露方法给父组件(Home.vue)调用
defineExpose({
  receiveFileFromReadModule
})
</script>

<style scoped>
.exam-module-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  min-height: 0;
  background: #FFFFFF;
}

.panel-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;
}
</style>