<template>
  <div class="generation-detail-page">
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="router.back()">返回</el-button>
        <h1>{{ generation?.name || '生成任务详情' }}</h1>
        <el-tag :type="getStatusType(generation?.status)" size="large">
          {{ getStatusLabel(generation?.status) }}
        </el-tag>
      </div>
      <div class="header-right">
        <el-button v-if="generation?.status === 'pending'" @click="executeExtraction">
          开始提取
        </el-button>
        <el-button v-if="generation?.status === 'review'" type="success" @click="confirmGeneration">
          确认生成
        </el-button>
        <el-button v-if="generation?.status === 'completed'" type="primary" @click="downloadDocument">
          下载文档
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 变量提取结果 -->
        <div class="card section">
          <div class="section-header">
            <h3>变量提取结果</h3>
            <el-tag v-if="generation?.status === 'extracting'">
              提取中 {{ generation?.progress }}%
            </el-tag>
          </div>

          <el-progress
            v-if="generation?.status === 'extracting'"
            :percentage="generation?.progress"
            :stroke-width="8"
            class="progress-bar"
          />

          <el-table :data="variableValues" stripe>
            <el-table-column prop="displayName" label="变量名" width="150" />
            <el-table-column prop="value" label="提取值">
              <template #default="{ row }">
                <el-input
                  v-if="generation?.status === 'review'"
                  v-model="row.value"
                  size="small"
                  @change="markAsModified(row)"
                />
                <span v-else>{{ row.value || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="confidence" label="置信度" width="100">
              <template #default="{ row }">
                <el-progress
                  :percentage="row.confidence * 100"
                  :stroke-width="6"
                  :color="getConfidenceColor(row.confidence)"
                  :show-text="false"
                />
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getVariableStatusType(row.status)" size="small">
                  {{ getVariableStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>

      <el-col :span="8">
        <!-- 基本信息 -->
        <div class="card section">
          <h3>任务信息</h3>
          <div class="info-item">
            <span class="info-label">使用模板</span>
            <span class="info-value">{{ generation?.templateName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建时间</span>
            <span class="info-value">{{ generation?.createTime }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">变量数量</span>
            <span class="info-value">{{ variableValues.length }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">任务状态</span>
            <span class="info-value">
              <el-tag :type="getStatusType(generation?.status)" size="small">
                {{ getStatusLabel(generation?.status) }}
              </el-tag>
            </span>
          </div>
        </div>

        <!-- 来源文件 -->
        <div class="card section">
          <h3>来源文件</h3>
          <div class="source-file-list">
            <div v-for="(docId, alias) in sourceFileMap" :key="alias" class="source-file-item">
              <span class="sf-icon">📄</span>
              <div class="sf-info">
                <div class="sf-name">{{ alias }}</div>
                <div class="sf-id">{{ docId }}</div>
              </div>
              <el-button size="small" :icon="View">查看</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { generationApi } from '@/api'

const router = useRouter()
const route = useRoute()
const generationId = route.params.id

const loading = ref(false)

// 从 API 获取数据
const generation = ref(null)
const sourceFileMap = ref({})
const variableValues = ref([])

onMounted(async () => {
  await fetchGenerationDetail()
})

async function fetchGenerationDetail() {
  loading.value = true
  try {
    const data = await generationApi.getById(generationId)
    generation.value = {
      ...data,
      templateName: data.templateName || '未知模板',
      progress: data.status === 'completed' ? 100 : (data.status === 'extracting' ? 50 : 0)
    }
    
    // 解析来源文件映射
    sourceFileMap.value = data.sourceFileMap || {}
    
    // 解析提取结果
    const extractedValues = data.extractedValues || {}
    variableValues.value = Object.entries(extractedValues).map(([name, val]) => ({
      name,
      displayName: val.displayName || name,
      value: val.value || '',
      confidence: val.confidence || 0,
      status: val.value ? 'extracted' : 'pending'
    }))
  } catch (error) {
    console.error('获取生成任务详情失败:', error)
    ElMessage.error('获取生成任务详情失败')
  } finally {
    loading.value = false
  }
}

function getStatusType(status) {
  const map = {
    pending: 'info',
    extracting: 'warning',
    review: '',
    completed: 'success',
    error: 'danger'
  }
  return map[status] || 'info'
}

function getStatusLabel(status) {
  const map = {
    pending: '待执行',
    extracting: '提取中',
    review: '待确认',
    completed: '已完成',
    error: '错误'
  }
  return map[status] || status
}

function getVariableStatusType(status) {
  const map = {
    extracted: 'success',
    modified: 'warning',
    low_confidence: '',
    pending: 'info',
    error: 'danger'
  }
  return map[status] || 'info'
}

function getVariableStatusLabel(status) {
  const map = {
    extracted: '已提取',
    modified: '已修改',
    low_confidence: '低置信',
    pending: '待提取',
    error: '错误'
  }
  return map[status] || status
}

function getConfidenceColor(confidence) {
  if (confidence >= 0.8) return '#52c41a'
  if (confidence >= 0.5) return '#faad14'
  return '#ff4d4f'
}

function markAsModified(row) {
  row.status = 'modified'
}

async function executeExtraction() {
  try {
    generation.value.status = 'extracting'
    generation.value.progress = 0
    
    await generationApi.execute(generationId)
    
    // 轮询进度
    const interval = setInterval(async () => {
      try {
        const progress = await generationApi.getProgress(generationId)
        generation.value.progress = progress.progress || 0
        generation.value.status = progress.status
        
        if (progress.status === 'review' || progress.status === 'completed' || progress.status === 'error') {
          clearInterval(interval)
          await fetchGenerationDetail() // 重新获取完整数据
          ElMessage.success('变量提取完成')
        }
      } catch {
        clearInterval(interval)
      }
    }, 2000)
  } catch (error) {
    ElMessage.error('执行失败: ' + error.message)
    generation.value.status = 'error'
  }
}

async function confirmGeneration() {
  try {
    await generationApi.confirm(generationId)
    generation.value.status = 'completed'
    ElMessage.success('文档生成成功')
  } catch (error) {
    ElMessage.error('生成失败: ' + error.message)
  }
}

function downloadDocument() {
  const url = generationApi.getDownloadUrl(generationId)
  window.open(url, '_blank')
}
</script>

<style lang="scss" scoped>
.generation-detail-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    h1 {
      font-size: 20px;
      margin: 0;
    }
  }

  .header-right {
    display: flex;
    gap: 8px;
  }
}

.section {
  padding: 20px;
  margin-bottom: 20px;

  h3 {
    font-size: 15px;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border);

    h3 {
      margin: 0;
      border: none;
      padding: 0;
    }
  }
}

.progress-bar {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid var(--border);

  &:last-child {
    border-bottom: none;
  }

  .info-label {
    color: var(--text-2);
  }

  .info-value {
    font-weight: 500;
  }
}

.source-file-list {
  .source-file-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background: var(--bg);
    border-radius: 8px;
    margin-bottom: 8px;

    .sf-icon {
      font-size: 24px;
    }

    .sf-info {
      flex: 1;

      .sf-name {
        font-weight: 600;
        margin-bottom: 2px;
      }

      .sf-id {
        font-size: 11px;
        color: var(--text-3);
        font-family: monospace;
      }
    }
  }
}
</style>
