<template>
  <div class="template-panel">
    <el-collapse v-model="activeCollapse">
      <!-- 模板列表 -->
      <TemplateListSection 
        @template-applied="handleTemplateApplied"
      />
      
      <!-- 数据源选择 -->
      <DataSourceSection 
        @data-source-selected="handleDataSourceSelected"
      />
      
      <!-- 目录浏览 -->
      <DirectoryBrowserSection 
        @files-scanned="handleFilesScanned"
      />
      
      <!-- 批量处理 -->
      <BatchProcessSection 
        @batch-started="handleBatchStarted"
      />
      
      <!-- 文件列表 -->
      <FileListSection 
        @loadFile="emit('loadFile', $event)"
      />
    </el-collapse>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useEditorStore, useTemplateStore } from '@/stores'
import { 
  useTemplate, 
  useDirectory, 
  useDataSource,
  useBatchProcess
} from './template-panel/composables'

// 子组件导入
import TemplateListSection from './template-panel/TemplateListSection.vue'
import DataSourceSection from './template-panel/DataSourceSection.vue'
import DirectoryBrowserSection from './template-panel/DirectoryBrowserSection.vue'
import BatchProcessSection from './template-panel/BatchProcessSection.vue'
import FileListSection from './template-panel/FileListSection.vue'

const editorStore = useEditorStore()
const templateStore = useTemplateStore()

// UI 状态
const activeCollapse = ref(['templates', 'data-sources'])

// 初始化 Composables（用于事件回调）
const {
  loadTemplates,
  loadDataSources,
  selectDataSource
} = useDataSource()

const {
  browsePath
} = useDirectory()

// 事件定义
const emit = defineEmits<{
  loadFile: [payload: { imagePath: string; jsonPath: string }]
}>()

// 事件处理器
function handleTemplateApplied() {
  // 模板已应用，重新加载模板列表
  loadTemplates()
}

async function handleDataSourceSelected() {
  // 数据源已选择，自动展开目录浏览
  if (!activeCollapse.value.includes('directory')) {
    activeCollapse.value.push('directory')
  }
}

async function handleFilesScanned() {
  // 文件扫描完成，自动展开文件列表
  if (!activeCollapse.value.includes('files')) {
    activeCollapse.value.push('files')
  }
}

async function handleBatchStarted() {
  // 批量处理开始，自动展开批量处理面板查看结果
  if (!activeCollapse.value.includes('batch')) {
    activeCollapse.value.push('batch')
  }
}

// 初始化
onMounted(async () => {
  await loadTemplates()
  await loadDataSources()
  await browsePath('~')
})
</script>

<style scoped lang="scss">
.template-panel {
  padding: 12px;
}
</style>
