<template>
  <el-collapse-item 
    v-if="templateStore.hasFilePairs && editorStore.hasData" 
    title="批量处理" 
    name="batch"
  >
    <div class="batch-processor">
      <el-alert 
        type="warning" 
        :closable="false"
        show-icon
        style="margin-bottom: 12px"
      >
        <template #title>
          使用选定模板的列结构应用到所有文件
        </template>
      </el-alert>
      
      <div class="batch-info">
        <div class="info-item">
          <label>选择模板:</label>
          <el-select 
            v-model="selectedTemplateName"
            placeholder="请从已保存模板中选择"
            style="flex: 1"
            @change="onTemplateSelect"
          >
            <el-option 
              v-for="tpl in templateList" 
              :key="tpl.name" 
              :label="`${tpl.name} (${tpl.stats?.col_count || 0} 列)`"
              :value="tpl.name"
            />
          </el-select>
        </div>
        <div class="info-item">
          <label>数据源:</label>
          <span>{{ templateStore.activeDataSourceName || '手动配置' }}</span>
        </div>
        <div class="info-item">
          <label>待处理文件:</label>
          <span>{{ templateStore.filePairs.length }} 个</span>
        </div>
        <div class="info-item">
          <label>模板列数:</label>
          <span>{{ selectedTemplateColCount }} 列</span>
        </div>
      </div>
      
      <div class="batch-options">
        <el-form label-width="100px" size="small">
          <el-form-item label="自适应行">
            <el-switch v-model="batchConfig.adjustRows" />
            <span class="option-desc">每页根据实际内容调整行高度</span>
          </el-form-item>
          <el-form-item label="并行处理">
            <el-switch v-model="batchConfig.parallel" />
            <span class="option-desc">加速处理，推荐开启</span>
          </el-form-item>
          <el-form-item label="绘制表格线">
            <el-switch v-model="batchConfig.drawLines" />
            <span class="option-desc">保存可视化结果图片</span>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="batch-actions">
        <el-button 
          type="primary" 
          size="default"
          @click="handleStartBatchProcess"
          :loading="isBatchProcessing"
          :disabled="!canStartBatch || !selectedTemplateName"
        >
          <el-icon><VideoPlay /></el-icon>
          开始批量处理
        </el-button>
        <el-button 
          size="default"
          @click="resetBatchState"
          :disabled="isBatchProcessing"
        >
          重置
        </el-button>
      </div>
      
      <!-- 进度条 -->
      <div v-if="batchProgress.total > 0" class="batch-progress">
        <el-progress 
          :percentage="batchProgressPercentage" 
          :status="batchProgressStatus"
        >
          <span>{{ batchProgress.processed }} / {{ batchProgress.total }}</span>
        </el-progress>
        
        <div class="progress-stats">
          <el-tag type="success">成功: {{ batchProgress.success }}</el-tag>
          <el-tag type="danger">失败: {{ batchProgress.failed }}</el-tag>
        </div>
      </div>
      
      <!-- 结果展示 -->
      <div v-if="batchResults.length > 0" class="batch-results">
        <div class="results-header">
          <span>处理结果</span>
          <el-button size="small" text @click="batchResults = []">清除</el-button>
        </div>
        <div class="results-list">
          <div 
            v-for="(result, index) in batchResults" 
            :key="index"
            class="result-item"
            :class="{ success: result.success, failed: !result.success }"
          >
            <el-icon v-if="result.success"><CircleCheck /></el-icon>
            <el-icon v-else><CircleClose /></el-icon>
            <span class="filename">{{ result.filename }}</span>
            <span v-if="result.success && result.rows" class="result-meta">
              {{ result.rows }} 行 × {{ result.cols }} 列
            </span>
            <span v-if="!result.success && result.error" class="error-msg">
              {{ result.error }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </el-collapse-item>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { VideoPlay, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useEditorStore, useTemplateStore } from '@/stores'
import { useBatchProcess } from './composables'
import { templateApi } from '@/api'

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

const selectedTemplateName = ref<string>('')
const templateList = ref<any[]>([])
const isLoadingTemplates = ref(false)

const {
  isBatchProcessing,
  batchConfig,
  batchProgress,
  batchResults,
  canStartBatch,
  batchProgressPercentage,
  batchProgressStatus,
  startBatchProcess: originalStartBatchProcess,
  resetBatchState
} = useBatchProcess()

const emit = defineEmits<{
  batchStarted: []
}>()

const selectedTemplateColCount = computed(() => {
  if (!selectedTemplateName.value) return 0
  const tpl = templateList.value.find(t => t.name === selectedTemplateName.value)
  return tpl?.stats?.col_count || 0
})

// 加载模板列表
async function loadTemplates() {
  isLoadingTemplates.value = true
  try {
    const templates = await templateApi.listTemplates()
    templateList.value = templates || []
    
    if (templateList.value.length === 0) {
      ElMessage.info('暂无已保存的模板，请先创建模板')
    }
  } catch (error: any) {
    ElMessage.error(`加载模板列表失败: ${error.message}`)
  } finally {
    isLoadingTemplates.value = false
  }
}

// 模板选择变更
function onTemplateSelect(templateName: string) {
  selectedTemplateName.value = templateName
}

// 处理开始批量处理
async function handleStartBatchProcess() {
  if (!selectedTemplateName.value) {
    ElMessage.warning('请先选择模板')
    return
  }

  await originalStartBatchProcess(selectedTemplateName.value)
  emit('batchStarted')
}

// 组件挂载时加载模板
onMounted(() => {
  loadTemplates()
})

</script>

<style scoped>
.batch-processor {
  .batch-info {
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 12px;
    
    .info-item {
      display: flex;
      gap: 8px;
      align-items: center;
      margin-bottom: 8px;
      font-size: 13px;
      
      &:first-child {
        align-items: flex-start;
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      label {
        color: #909399;
        min-width: 90px;
        flex-shrink: 0;
      }
      
      span {
        color: #303133;
        font-weight: 500;
      }
      
      :deep(.el-select) {
        flex: 1;
      }
    }
  }
  
  .batch-options {
    margin-bottom: 12px;
    
    .option-desc {
      font-size: 12px;
      color: #909399;
      margin-left: 8px;
    }
  }
  
  .batch-actions {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
  }
  
  .batch-progress {
    margin-bottom: 16px;
    
    .progress-stats {
      display: flex;
      gap: 8px;
      margin-top: 8px;
    }
  }
  
  .batch-results {
    .results-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-weight: 600;
      color: #303133;
    }
    
    .results-list {
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }
    
    .result-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      border-bottom: 1px solid #f5f7fa;
      font-size: 12px;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.success {
        color: #67c23a;
      }
      
      &.failed {
        color: #f56c6c;
      }
      
      .filename {
        flex: 1;
        color: #303133;
      }
      
      .result-meta {
        color: #909399;
        font-size: 11px;
      }
      
      .error-msg {
        color: #f56c6c;
        font-size: 11px;
      }
    }
  }
}
</style>
