/**
 * 批量处理 Composable
 * 负责批量处理的配置、执行和进度跟踪
 */

import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTemplateStore, useEditorStore } from '@/stores'
import { batchApi } from '@/api'

interface BatchConfig {
  adjustRows: boolean
  parallel: boolean
  drawLines: boolean
}

interface BatchProgress {
  total: number
  processed: number
  success: number
  failed: number
}

interface BatchResult {
  success: boolean
  filename: string
  rows?: number
  cols?: number
  error?: string
}

export function useBatchProcess() {
  const templateStore = useTemplateStore()
  const editorStore = useEditorStore()
  
  // 状态
  const isBatchProcessing = ref(false)
  const batchConfig = ref<BatchConfig>({
    adjustRows: true,
    parallel: true,
    drawLines: false
  })
  const batchProgress = ref<BatchProgress>({
    total: 0,
    processed: 0,
    success: 0,
    failed: 0
  })
  const batchResults = ref<BatchResult[]>([])
  
  // 计算属性
  const canStartBatch = computed(() => {
    return templateStore.hasFilePairs && 
           editorStore.hasData && 
           !isBatchProcessing.value &&
           templateStore.scanConfig.outputDir
  })
  
  const batchProgressPercentage = computed(() => {
    if (batchProgress.value.total === 0) return 0
    return Math.round((batchProgress.value.processed / batchProgress.value.total) * 100)
  })
  
  const batchProgressStatus = computed(() => {
    if (batchProgress.value.failed > 0) return 'exception'
    if (batchProgress.value.processed === batchProgress.value.total && 
        batchProgress.value.total > 0) {
      return 'success'
    }
    return undefined
  })
  
  const hasResults = computed(() => batchResults.value.length > 0)
  
  const successCount = computed(() => batchProgress.value.success)
  const failedCount = computed(() => batchProgress.value.failed)
  
  /**
   * 开始批量处理（接收模板名称参数）
   */
  async function startBatchProcess(templateName: string) {
    if (!canStartBatch.value) {
      ElMessage.warning('请先加载数据并扫描文件')
      return false
    }

    if (!templateName || templateName.trim() === '') {
      ElMessage.warning('请先选择模板')
      return false
    }

    try {
      await ElMessageBox.confirm(
        `确定要批量处理 ${templateStore.filePairs.length} 个文件吗？将使用模板"${templateName}"应用列结构。`,
        '确认批量处理',
        { type: 'warning' }
      )
    } catch {
      return false
    }

    isBatchProcessing.value = true
    batchProgress.value = {
      total: templateStore.filePairs.length,
      processed: 0,
      success: 0,
      failed: 0
    }
    batchResults.value = []

    try {
      const response = await batchApi.batchProcess({
        template_name: templateName,
        file_pairs: templateStore.filePairs.map(pair => ({
          json_path: pair.json_path,
          image_path: pair.image_path
        })),
        output_dir: templateStore.scanConfig.outputDir,
        parallel: batchConfig.value.parallel,
        adjust_rows: batchConfig.value.adjustRows
      })

      // 更新进度
      batchProgress.value.processed = response.processed
      batchProgress.value.success = response.results.filter(r => r.success).length
      batchProgress.value.failed = response.results.filter(r => !r.success).length

      // 保存结果
      batchResults.value = response.results.map(r => ({
        success: r.success,
        filename: r.filename || '未知',
        rows: r.rows,
        cols: r.cols,
        error: r.error
      }))

      ElMessage.success(
        `批量处理完成: 成功 ${batchProgress.value.success}/${batchProgress.value.total}`
      )

      // 如果需要绘制表格线
      if (batchConfig.value.drawLines && batchProgress.value.success > 0) {
        await drawBatchLines(response.results.filter(r => r.success))
      }

      return {
        success: true,
        results: batchResults.value
      }
    } catch (error: any) {
      ElMessage.error(`批量处理失败: ${error.message}`)
      return {
        success: false,
        error: error.message
      }
    } finally {
      isBatchProcessing.value = false
    }
  }
  
  /**
   * 绘制批量处理的表格线
   */
  async function drawBatchLines(successResults: any[]) {
    try {
      await batchApi.batchDraw({
        results: successResults,
        line_width: 2,
        line_color: [0, 0, 0]
      })
      ElMessage.success('表格线绘制完成')
      return true
    } catch (error: any) {
      ElMessage.error(`绘制表格线失败: ${error.message}`)
      return false
    }
  }
  
  /**
   * 重置批量处理状态
   */
  function resetBatchState() {
    batchProgress.value = {
      total: 0,
      processed: 0,
      success: 0,
      failed: 0
    }
    batchResults.value = []
  }
  
  /**
   * 清除批量结果
   */
  function clearResults() {
    batchResults.value = []
  }
  
  /**
   * 更新批量配置
   */
  function updateConfig(config: Partial<BatchConfig>) {
    batchConfig.value = { ...batchConfig.value, ...config }
  }
  
  return {
    // 状态
    isBatchProcessing,
    batchConfig,
    batchProgress,
    batchResults,
    
    // 计算属性
    canStartBatch,
    batchProgressPercentage,
    batchProgressStatus,
    hasResults,
    successCount,
    failedCount,
    
    // 方法
    startBatchProcess,
    resetBatchState,
    clearResults,
    updateConfig
  }
}
