<template>
  <div class="batch-job-manager">
    <div class="page-header">
      <div class="header-title">
        <i class="fas fa-tasks"></i>
        <h2>批量处理任务管线</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" size="large" @click="openWizard">
          <i class="fas fa-plus"></i> 创建批量任务
        </el-button>
      </div>
    </div>

    <div class="dashboard-content">
      <!-- 任务概览卡片 -->
      <div class="overview-cards">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-spinner fa-spin"></i></div>
          <div class="stat-info">
            <div class="stat-value">{{ jobs.filter(j => j.status === 'running').length }}</div>
            <div class="stat-label">运行中任务</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
          <div class="stat-info">
            <div class="stat-value">{{ jobs.filter(j => ['completed', 'completed_with_errors'].includes(j.status)).length }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon warning"><i class="fas fa-clock"></i></div>
          <div class="stat-info">
            <div class="stat-value">{{ jobs.filter(j => j.status === 'pending').length }}</div>
            <div class="stat-label">排队中</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon danger"><i class="fas fa-times-circle"></i></div>
          <div class="stat-info">
            <div class="stat-value">{{ jobs.filter(j => j.status === 'failed').length }}</div>
            <div class="stat-label">失败/异常</div>
          </div>
        </div>
      </div>

      <!-- 任务列表 -->
      <div class="job-list-section card-panel">
        <div class="section-header">
          <h3>任务历史与调度队列</h3>
          <div class="filter-group">
            <el-select v-model="statusFilter" placeholder="状态过滤" size="small">
              <el-option label="全部" value="all" />
              <el-option label="待执行" value="pending" />
              <el-option label="运行中" value="running" />
              <el-option label="已完成" value="completed" />
              <el-option label="失败/异常" value="failed" />
            </el-select>
          </div>
        </div>
        <el-table :data="filteredJobs" style="width: 100%" stripe>
          <!-- 展开项：显示具体的子条目 -->
          <el-table-column type="expand">
            <template #default="scope">
              <div style="padding: 10px 40px;">
                <h4 style="margin-top: 0; margin-bottom: 15px; color: var(--color-text-secondary);">批次明细 (模型条目)</h4>
                <el-table :data="scope.row.items" size="small" border>
                  <el-table-column prop="modelPath" label="模型路径" show-overflow-tooltip />
                  <el-table-column prop="status" label="执行状态" width="150">
                    <template #default="itemScope">
                      <el-tag :type="getItemStatusType(itemScope.row.status)" size="small">
                        {{ getItemStatusLabel(itemScope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="finishedAt" label="完成时间" width="160" />
                  <el-table-column prop="errorMessage" label="错误信息" show-overflow-tooltip>
                    <template #default="itemScope">
                      <span v-if="itemScope.row.errorMessage" style="color: #F56C6C">{{ itemScope.row.errorMessage }}</span>
                      <span v-else class="text-gray-400">-</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="batchId" label="批次ID" width="120" />
          <el-table-column prop="strategy" label="执行策略" width="150" />
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="scope">
              <el-tag :type="getPriorityType(scope.row.priority)" size="small">
                {{ scope.row.priority }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="进度" width="200">
            <template #default="scope">
              <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.status)" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="模型数量" width="100">
            <template #default="scope">
              {{ scope.row.completedCount }} / {{ scope.row.totalCount }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" />
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="scope">
              <!-- 取消已支持：如果不是终态则允许取消 -->
              <el-button v-if="['running', 'pending'].includes(scope.row.status)" type="danger" size="small" link @click="cancelJob(scope.row)">取消批次</el-button>
              <el-button v-if="['completed', 'completed_with_errors', 'failed'].includes(scope.row.status)" type="primary" size="small" link @click="viewDetails(scope.row)">详情与报告</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 创建任务向导对话框 -->
    <el-dialog v-model="wizardVisible" title="创建批量任务" width="700px" destroy-on-close>
      <el-steps :active="wizardStep" finish-status="success" align-center class="wizard-steps">
        <el-step title="选择模型" description="选择要处理的文件/目录"></el-step>
        <el-step title="配置策略" description="选择批处理动作指令"></el-step>
        <el-step title="调度设置" description="设置优先级与排队模式"></el-step>
      </el-steps>

      <div class="wizard-content">
        <!-- 步骤1：选择模型 -->
        <div v-show="wizardStep === 0" class="step-panel">
          <p class="step-desc">请输入模型路径并点击“增加模型”，构建本次批处理的模型列表（支持 .prt, .rvt 扩展名）：</p>
          <div class="model-path-input-row">
            <el-input
              v-model="newModelPath"
              placeholder="例如：C:\CAD\project\part1.prt 或 D:\BIM\model.rvt"
              @keyup.enter="addModelPath"
            />
            <el-button type="primary" @click="addModelPath">
              <i class="fas fa-plus"></i> 增加模型
            </el-button>
          </div>
          <div class="model-path-list" v-if="taskForm.modelPaths.length > 0">
            <div class="model-path-item" v-for="(path, index) in taskForm.modelPaths" :key="path + index">
              <span class="path-text">{{ path }}</span>
              <el-button type="danger" size="small" link @click="removeModelPath(index)">移除</el-button>
            </div>
          </div>
          <div class="empty-model-paths" v-else>
            尚未添加模型路径
          </div>
        </div>

        <!-- 步骤2：配置策略 -->
        <div v-show="wizardStep === 1" class="step-panel">
          <p class="step-desc" v-if="detectedCadTypes.length === 0">尚未检测到支持配置的CAD文件模型或缺少模型。</p>
          <el-form label-width="120px">
            <template v-for="cadType in detectedCadTypes" :key="cadType">
              <div class="cad-type-block">
                <el-divider content-position="left">
                  <i class="fas" :class="cadType === 'creo' ? 'fa-cube' : (cadType === 'revit' ? 'fa-building' : 'fa-cogs')"></i>
                  {{ cadType === 'creo' ? 'Creo 模型配置 (.prt, .asm)' : (cadType === 'revit' ? 'Revit 模型配置 (.rvt, .rfa)' : 'PDMS 模型配置 (.sam, .mdb)') }}
                </el-divider>
                
                <el-form-item label="执行策略序列">
                  <el-select v-model="cadSettings[cadType].strategy" placeholder="请选择策略" style="width: 100%" @change="(val) => onStrategyChange(cadType, val)">
                    <template v-if="cadType === 'creo'">
                      <el-option label="模型打开 -> 几何优化 -> 关闭模型 (Creo)" value="creo_shrinkwrap" />
                    </template>
                    <template v-else-if="cadType === 'revit'">
                      <el-option label="模型打开 -> 建筑模型剥壳 -> 关闭模型 (Revit)" value="shell_execute" />
                    </template>
                    <template v-else-if="cadType === 'pdms'">
                      <el-option label="工程打开 -> 模型包裹化防泄密 -> 占位关闭 (PDMS)" value="pdms_shrinkwrap" />
                      <el-option label="工程打开 -> 模型参数化简化 -> 占位关闭 (PDMS)" value="pdms_simplify" />
                    </template>
                  </el-select>
                </el-form-item>

                <div class="strategy-params" v-if="cadSettings[cadType].strategy">
                  <template v-if="cadSettings[cadType].strategy === 'creo_shrinkwrap'">
                    <el-form-item label="轻量化质量">
                      <el-slider v-model="cadSettings[cadType].params.quality" :min="1" :max="10" show-input style="max-width: 400px;"></el-slider>
                    </el-form-item>
                    <el-form-item label="导出格式">
                      <el-select v-model="cadSettings[cadType].params.exportFormat" placeholder="输出格式" style="width: 200px">
                        <el-option label="默认 (.prt / .asm)" value="default" />
                        <el-option label="STEP (.stp)" value="step" />
                        <el-option label="IGES (.igs)" value="iges" />
                        <el-option label="OBJ (.obj)" value="obj" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="高级过滤">
                      <el-checkbox v-model="cadSettings[cadType].params.ignoreSkeletons">忽略骨架</el-checkbox>
                      <el-checkbox v-model="cadSettings[cadType].params.ignoreQuilts">忽略面组 (Quilts)</el-checkbox>
                      <el-checkbox v-model="cadSettings[cadType].params.fillHoles">自动补孔</el-checkbox>
                    </el-form-item>
                  </template>

                  <template v-else-if="cadSettings[cadType].strategy === 'shell_execute'">
                    <el-form-item label="处理模式">
                      <el-select v-model="cadSettings[cadType].params.mode" placeholder="请选择模式" style="width: 250px">
                        <el-option label="保守保留 (Conservative)" value="Conservative" />
                        <el-option label="标准平衡 (Standard)" value="Standard" />
                        <el-option label="激进删除 (Aggressive)" value="Aggressive" />
                        <el-option label="仅保留外壳 (EnvelopeOnly)" value="EnvelopeOnly" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="备份原文件">
                      <el-switch v-model="cadSettings[cadType].params.backupOriginal" active-text="是" inactive-text="否" />
                    </el-form-item>
                  </template>
                  
                  <template v-else-if="cadSettings[cadType].strategy.includes('pdms')">
                    <el-form-item label="层级保留">
                      <el-input v-model="cadSettings[cadType].params.levelFilter" placeholder="例如: /SITE/ZONE" style="width: 250px" />
                    </el-form-item>
                    <el-form-item label="移除管道附件">
                      <el-switch v-model="cadSettings[cadType].params.removeAttachments" />
                    </el-form-item>
                  </template>
                </div>
              </div>
            </template>
          </el-form>
        </div>

        <!-- 步骤3：调度设置 -->
        <div v-show="wizardStep === 2" class="step-panel">
          <el-form :model="taskForm" label-width="120px">
            <el-form-item label="任务优先级">
              <el-radio-group v-model="taskForm.priority">
                <el-radio label="低">低</el-radio>
                <el-radio label="普通">普通</el-radio>
                <el-radio label="高">高</el-radio>
                <el-radio label="紧急">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="排队模式">
               <el-tag type="info">全局严格单队列 FIFO 串行执行</el-tag>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="wizardStep > 0" @click="wizardStep--">上一步</el-button>
          <el-button v-if="wizardStep < 2" type="primary" @click="wizardStep++">下一步</el-button>
          <el-button v-if="wizardStep === 2" type="success" @click="submitTask">提交调度批次</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import websocketService from '@/services/websocketService'

// 模拟状态
const statusFilter = ref('all')
const wizardVisible = ref(false)
const wizardStep = ref(0)
const taskForm = ref({
  priority: '普通',
  modelPaths: []
})

const cadSettings = ref({
  creo: {
    strategy: 'creo_shrinkwrap',
    params: { quality: 5, exportFormat: 'step', ignoreSkeletons: true, ignoreQuilts: false, fillHoles: false }
  },
  revit: {
    strategy: 'shell_execute',
    params: { mode: 'EnvelopeOnly', backupOriginal: false }
  },
  pdms: {
    strategy: 'pdms_simplify',
    params: { levelFilter: '', removeAttachments: true }
  }
})

const getCadType = (path) => {
  const ext = path.split('.').pop().toLowerCase();
  if (['prt', 'asm'].includes(ext)) return 'creo';
  if (['rvt', 'rfa'].includes(ext)) return 'revit';
  if (['sam', 'mdb'].includes(ext)) return 'pdms';
  return 'unknown';
}

const detectedCadTypes = computed(() => {
  const types = new Set();
  taskForm.value.modelPaths.forEach(p => {
    const t = getCadType(p);
    if (t !== 'unknown') types.add(t);
  })
  return Array.from(types);
})

const newModelPath = ref('')

// 队列数据及过滤
const jobs = ref([])

const filteredJobs = computed(() => {
  if (statusFilter.value === 'all') return jobs.value
  return jobs.value.filter(j => j.status === statusFilter.value)
})

// === WebSocket 模拟与生命周期 ===
const activeBatchIds = new Set()
let pollTimer = null

const handleWsMessage = (msg) => {
  if (msg.type === 'batch_created' || msg.type === 'batch_completed') {
    if (msg.data && msg.data.batch) {
      updateBatchInJobs(msg.data.batch, msg.data.items || [])
    }
  } else if (msg.type === 'batch_item_update') {
    if (msg.data && msg.data.batch && msg.data.item) {
      mergeBatchItemUpdate(msg.data.batch, msg.data.item)
    }
  } else if (msg.type === 'info' && msg.data && msg.data.batch) {
    // Check if backend uses generic info or batch_status_response for updates
    updateBatchInJobs(msg.data.batch, msg.data.items || [])
  }
}

const isTerminalBatchStatus = (status) => {
  return status === 'completed' || status === 'completed_with_errors' || status === 'failed'
}

const mapItemData = (it) => {
  return {
    id: it.id,
    modelPath: it.model_path,
    taskType: it.task_type,
    status: it.status,
    retry: `${it.retry_count || 0}/${it.max_retries || 1}`,
    errorMessage: it.error_message || '',
    finishedAt: it.finished_at || it.started_at || it.created_at || '-'
  }
}

const updateBatchInJobs = (batchData, itemsData) => {
  const existingJob = jobs.value.find(j => j.batchId === batchData.id)
  
  const mappedItems = itemsData.map(mapItemData).sort((a,b) => {
    const aItem = itemsData.find(i => i.id === a.id)
    const bItem = itemsData.find(i => i.id === b.id)
    return (aItem?.sequence || 0) - (bItem?.sequence || 0)
  })

  const progressCalc = batchData.total_count ? Math.round(((batchData.succeeded_count + batchData.failed_count) / batchData.total_count) * 100) : 0

  if (existingJob) {
    existingJob.status = batchData.status
    existingJob.completedCount = batchData.succeeded_count + batchData.failed_count
    existingJob.totalCount = batchData.total_count
    existingJob.progress = progressCalc
    existingJob.items = mappedItems
  } else {
    jobs.value.unshift({
      batchId: batchData.id,
      strategy: batchData.metadata?.strategy || batchData.name || '批量处理',
      priority: batchData.metadata?.priority || '普通',
      progress: progressCalc,
      status: batchData.status,
      totalCount: batchData.total_count || 0,
      completedCount: (batchData.succeeded_count || 0) + (batchData.failed_count || 0),
      createdAt: new Date(batchData.created_at).toLocaleString(),
      items: mappedItems,
      rawBatch: batchData
    })
  }

  managePolling(batchData)
}

const mergeBatchItemUpdate = (batchData, itemData) => {
  const existingJob = jobs.value.find(j => j.batchId === batchData.id)
  if (!existingJob) {
    // 如果还没记录，可能错过了 batch_created，进行一次获取全量状态
    websocketService.send({ type: 'get_batch_status', batch_id: batchData.id })
    return
  }

  existingJob.status = batchData.status
  existingJob.completedCount = batchData.succeeded_count + batchData.failed_count
  existingJob.totalCount = batchData.total_count
  existingJob.progress = batchData.total_count ? Math.round((existingJob.completedCount / batchData.total_count) * 100) : 0

  const mappedItem = mapItemData(itemData)
  const itemIndex = existingJob.items.findIndex(it => it.id === itemData.id)

  if (itemIndex > -1) {
    existingJob.items.splice(itemIndex, 1, mappedItem)
  } else {
    existingJob.items.push(mappedItem)
  }

  managePolling(batchData)
}

const managePolling = (batchData) => {
  if (!isTerminalBatchStatus(batchData.status)) {
    activeBatchIds.add(batchData.id)
  } else {
    activeBatchIds.delete(batchData.id)
  }

  if (activeBatchIds.size > 0 && !pollTimer) {
    pollTimer = window.setInterval(() => {
      activeBatchIds.forEach(id => {
        websocketService.send({ type: 'get_batch_status', batch_id: id })
      })
    }, 4000)
  } else if (activeBatchIds.size === 0 && pollTimer) {
    window.clearInterval(pollTimer)
    pollTimer = null
  }
}

onMounted(() => {
  websocketService.on('onMessage', handleWsMessage)
})

onUnmounted(() => {
  websocketService.off('onMessage', handleWsMessage)
  if (pollTimer) {
    window.clearInterval(pollTimer)
    pollTimer = null
  }
})

// 向导控制
const openWizard = () => {
  wizardStep.value = 0
  taskForm.value = {
    priority: '普通',
    modelPaths: []
  }
  cadSettings.value = {
    creo: {
      strategy: 'creo_shrinkwrap',
      params: { quality: 5, exportFormat: 'step', ignoreSkeletons: true, ignoreQuilts: false, fillHoles: false }
    },
    revit: {
      strategy: 'shell_execute',
      params: { mode: 'EnvelopeOnly', backupOriginal: false }
    },
    pdms: {
      strategy: 'pdms_simplify',
      params: { levelFilter: '', removeAttachments: true }
    }
  }
  wizardVisible.value = true
}

const onStrategyChange = (cadType, val) => {
  if (val === 'creo_shrinkwrap') {
    cadSettings.value[cadType].params = { quality: 5, exportFormat: 'step', ignoreSkeletons: true, ignoreQuilts: false, fillHoles: false }
  } else if (val === 'shell_execute') {
    cadSettings.value[cadType].params = { mode: 'EnvelopeOnly', backupOriginal: false }
  } else if (val.includes('pdms')) {
    cadSettings.value[cadType].params = { levelFilter: '', removeAttachments: true }
  } else {
    cadSettings.value[cadType].params = {}
  }
}

const submitTask = () => {
  if (taskForm.value.modelPaths.length === 0) {
    ElMessage.warning('请先添加至少一个模型路径')
    wizardStep.value = 0
    return
  }

  const batchName = `B-${Date.now().toString().slice(-8)}`
  const strategiesUsed = detectedCadTypes.value.map(t => cadSettings.value[t].strategy).join(', ') || '混合组合策略'
  
  // 组装并发送 submit_batch_tasks WebSocket 消息给后端
  const items = taskForm.value.modelPaths.map(p => {
    const type = getCadType(p);
    let strategy = '';
    let params = {};
    if (type !== 'unknown') {
        strategy = cadSettings.value[type].strategy;
        params = cadSettings.value[type].params;
    }
    
    // 如果是Revit，并且没有特定参数，按接入文档建议
    if (type === 'revit' && (!strategy || strategy === 'revit_shell')) {
      strategy = 'shell_execute';
    }

    return {
      model_path: p,
      task_type: strategy,
      task_params: params // 注意：文档要求 task_params 而不是 params
    }
  })
  
  websocketService.send({
    type: 'submit_batch_tasks',
    batch_name: batchName,
    metadata: {
      strategy: strategiesUsed,
      priority: taskForm.value.priority
    },
    items: items
  })

  ElMessage.success('批量任务已成功提交至全局串行队列，等待状态同步...')
  wizardVisible.value = false
}

const addModelPath = () => {
  const path = newModelPath.value.trim()
  if (!path) return
  
  // 按照路由规范，增加简单的扩展名限制校验
  const lowerPath = path.toLowerCase();
  const validExtensions = ['.prt', '.asm', '.rvt', '.rfa', '.ifc', '.sam', '.mdb']
  const isValid = validExtensions.some(ext => lowerPath.endsWith(ext) || lowerPath.includes(ext))
  
  if (!isValid) {
    ElMessage.warning('不支持的扩展名。目前支持例如 .prt, .asm, .rvt, .rfa, .ifc, .sam, .mdb')
    // 实际生产中可以允许强制添加，或者更精准校验，这里模拟强限制
  }

  if (taskForm.value.modelPaths.includes(path)) {
    ElMessage.warning('该模型路径已存在')
    return
  }
  taskForm.value.modelPaths.push(path)
  newModelPath.value = ''
}

const removeModelPath = (index) => {
  taskForm.value.modelPaths.splice(index, 1)
}

// 格式辅助
const getStatusLabel = (status) => {
  const map = { pending: '待执行', running: '执行中', completed: '已完成', completed_with_errors: '部分失败', queued: '排队中', failed: '失败/异常' }
  return map[status] || status
}
const getStatusType = (status) => {
  const map = { pending: 'info', running: 'primary', completed: 'success', completed_with_errors: 'warning', queued: 'info', failed: 'danger' }
  return map[status] || 'info'
}
const getPriorityType = (priority) => {
  const map = { '低': 'info', '普通': 'primary', '高': 'warning', '紧急': 'danger' }
  return map[priority] || 'info'
}
const getProgressStatus = (status) => {
  if (status === 'completed') return 'success'
  if (status === 'completed_with_errors') return 'warning'
  if (status === 'failed') return 'exception'
  return '' /* running/queued 无特殊状态效果 */
}

// 子条目格式辅助
const getItemStatusLabel = (status) => {
  const map = { 
    queued: '排队中', 
    dispatching: '处理中', 
    waiting_callback: '等待插件回调', 
    succeeded: '成功', 
    failed: '失败' 
  }
  return map[status] || status
}
const getItemStatusType = (status) => {
  const map = { 
    queued: 'info', 
    dispatching: 'primary', 
    waiting_callback: 'warning', 
    succeeded: 'success', 
    failed: 'danger' 
  }
  return map[status] || 'info'
}

// 操作事件
const cancelJob = (row) => {
  ElMessageBox.confirm('确定取消该批次任务? 正在执行的条目可能无法撤回。', '警告', { type: 'warning' }).then(() => {
    // 模拟从列表移除，实际应通过 ws 接口发送取消批次指令
    jobs.value = jobs.value.filter(j => j.batchId !== row.batchId)
    ElMessage.success('批次任务已取消')
  }).catch(()=> {})
}
const viewDetails = (row) => {
  ElMessage.info(`跳转至报告视图，查看 ${row.batchId} 详情日志及完整失败日志`)
}
</script>

<style scoped>
.batch-job-manager {
  height: 100%;
  padding: var(--spacing-xl);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.header-title h2 {
  font-size: var(--font-size-2xl);
  font-weight: 600;
  margin: 0;
  background: linear-gradient(90deg, var(--color-primary), #8bc34a);
  -webkit-background-clip: text;
  color: transparent;
}

.header-title i {
  font-size: var(--font-size-2xl);
  color: var(--color-primary);
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-xl);
}

.stat-card {
  background: var(--color-bg-card);
  padding: var(--spacing-xl);
  border-radius: var(--size-border-radius-lg);
  border: 1px solid var(--color-border-primary);
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  box-shadow: var(--shadow-sm);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-md);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  background: rgba(var(--color-primary-rgb), 0.1);
  color: var(--color-primary);
}
.stat-icon.success { background: rgba(var(--color-success-rgb), 0.1); color: var(--color-success); }
.stat-icon.warning { background: rgba(var(--color-warning-rgb), 0.1); color: var(--color-warning); }
.stat-icon.danger { background: rgba(var(--color-error-rgb), 0.1); color: var(--color-error); }

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1.2;
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.card-panel {
  background: var(--color-bg-card);
  border-radius: var(--size-border-radius-lg);
  border: 1px solid var(--color-border-primary);
  padding: var(--spacing-xl);
  box-shadow: var(--shadow-sm);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
}

.section-header h3 {
  margin: 0;
  font-size: var(--font-size-xl);
  font-weight: 600;
}

.wizard-steps {
  margin-bottom: var(--spacing-2xl);
}

.step-panel {
  padding: var(--spacing-lg);
  min-height: 250px;
}

.step-desc {
  color: #4b5563;
  margin-bottom: var(--spacing-md);
}

.model-path-input-row {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-md);
}

.model-path-list {
  border: 1px solid #d1d5db;
  border-radius: var(--size-border-radius);
  background: #ffffff;
  max-height: 260px;
  overflow-y: auto;
}

.model-path-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--spacing-md);
  padding: 10px 12px;
  border-bottom: 1px solid #e5e7eb;
}

.model-path-item:last-child {
  border-bottom: none;
}

.path-text {
  flex: 1;
  color: #111827;
  font-size: var(--font-size-sm);
  word-break: break-all;
}

.empty-model-paths {
  color: #6b7280;
  font-size: var(--font-size-sm);
  padding: 10px 2px;
}

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: var(--color-text-tertiary);
}

.strategy-params {
  background: var(--color-bg-card-secondary, rgba(255,255,255,0.05));
  border-radius: var(--size-border-radius);
  padding: var(--spacing-md) var(--spacing-lg);
  margin-top: var(--spacing-md);
  border: 1px dashed var(--color-border-primary);
}

.strategy-params .el-divider {
  margin-top: 0;
  margin-bottom: var(--spacing-lg);
}

/* 覆盖 Element UI 为深色主题适配 */
:deep(.el-table) {
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-striped-bg-color: rgba(255, 255, 255, 0.08);
  --el-table-header-bg-color: var(--color-bg-primary);
  --el-table-border-color: var(--color-border-primary);
  --el-table-text-color: var(--color-text-primary);
  --el-table-header-text-color: var(--color-text-primary);
  --el-table-row-hover-bg-color: var(--color-white-rgb-05);
}

/* 修复浅色斑马纹导致的文字可读性问题 */
:deep(.el-table .el-table__row td.el-table__cell) {
  color: var(--color-text-primary);
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background-color: rgba(255, 255, 255, 0.12);
}

/* 展开行内容区域背景 */
:deep(.el-table__expanded-cell) {
  background-color: rgba(0, 0, 0, 0.2) !important;
}

/* 固定列默认会有独立背景，保持与行背景一致，避免发白 */
:deep(.el-table .el-table-fixed-column--left),
:deep(.el-table .el-table-fixed-column--right) {
  background-color: transparent !important;
}
</style>
