<template>
  <div class="generations-page">
    <div class="page-header">
      <h1>📋 生成记录</h1>
      <el-button type="primary" :icon="Plus" @click="showCreateDialog = true">
        新建生成任务
      </el-button>
    </div>

    <!-- 筛选 -->
    <div class="filter-bar">
      <el-select v-model="statusFilter" placeholder="全部状态" clearable style="width: 140px">
        <el-option label="待执行" value="pending" />
        <el-option label="提取中" value="extracting" />
        <el-option label="待确认" value="review" />
        <el-option label="已完成" value="completed" />
        <el-option label="错误" value="error" />
      </el-select>
      <el-input
        v-model="searchKeyword"
        placeholder="🔍 搜索..."
        clearable
        style="width: 240px"
      />
      <el-radio-group v-model="timeFilter" style="margin-left: auto">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 生成记录列表 -->
    <div class="generation-list" v-loading="loading">
      <div
        v-for="gen in filteredGenerations"
        :key="gen.id"
        class="generation-card card"
      >
        <div class="gen-header">
          <span class="gen-icon">📄</span>
          <span class="gen-name">{{ gen.name }}</span>
          <el-tag :type="getStatusType(gen.status)" size="small">
            {{ getStatusLabel(gen.status) }}
          </el-tag>
        </div>
        <div class="gen-meta">
          <span>📅 {{ gen.createTime }}</span>
          <span>🎨 {{ gen.templateName }}</span>
          <span>📊 {{ gen.variableCount }} 个变量</span>
        </div>
        <div class="gen-progress" v-if="gen.status === 'extracting'">
          <el-progress :percentage="gen.progress" :stroke-width="6" />
        </div>
        <div class="gen-actions">
          <el-button type="primary" size="small" @click="viewGeneration(gen)">
            查看详情
          </el-button>
          <el-button
            v-if="gen.status === 'pending'"
            size="small"
            @click="executeGeneration(gen)"
          >
            开始提取
          </el-button>
          <el-button
            v-if="gen.status === 'review'"
            type="success"
            size="small"
            @click="confirmGeneration(gen)"
          >
            确认生成
          </el-button>
          <el-button
            v-if="gen.status === 'completed'"
            size="small"
            @click="downloadGeneration(gen)"
          >
            下载文档
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && filteredGenerations.length === 0" description="暂无生成记录">
      <el-button type="primary" @click="showCreateDialog = true">创建生成任务</el-button>
    </el-empty>

    <!-- 创建生成任务对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建生成任务" width="600">
      <el-form :model="newGeneration" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="newGeneration.name" placeholder="可选，默认使用模板名称" />
        </el-form-item>
        <el-form-item label="选择模板" required>
          <el-select v-model="newGeneration.templateId" style="width: 100%" placeholder="请选择模板">
            <el-option
              v-for="tpl in templates"
              :key="tpl.id"
              :label="tpl.name"
              :value="tpl.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="来源文件" v-if="selectedTemplate">
          <div class="source-files-upload">
            <div
              v-for="sf in selectedTemplate.sourceFiles"
              :key="sf.id"
              class="source-file-item"
            >
              <div class="sf-info">
                <span class="sf-name">{{ sf.alias }}</span>
                <el-tag size="small" v-if="sf.required" type="danger">必需</el-tag>
              </div>
              <el-upload
                :action="`/api/v1/parse/upload`"
                :on-success="(res) => handleSourceFileUpload(sf.alias, res)"
                :show-file-list="false"
              >
                <el-button size="small" :icon="Upload">
                  {{ newGeneration.sourceFileMap[sf.alias] ? '已上传' : '上传文件' }}
                </el-button>
              </el-upload>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createGeneration" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { generationApi, templateApi, sourceFileApi } from '@/api'

const router = useRouter()

const loading = ref(false)
const creating = ref(false)
const statusFilter = ref('')
const searchKeyword = ref('')
const timeFilter = ref('all')
const showCreateDialog = ref(false)

// 从 API 获取数据
const generations = ref([])
const templates = ref([])

// 加载数据
onMounted(async () => {
  await Promise.all([fetchGenerations(), fetchTemplates()])
})

async function fetchGenerations() {
  loading.value = true
  try {
    const data = await generationApi.list()
    generations.value = (data.records || data || []).map(g => ({
      ...g,
      templateName: g.templateName || '未知模板',
      variableCount: g.extractedValues ? Object.keys(g.extractedValues).length : 0,
      progress: g.status === 'completed' ? 100 : (g.status === 'extracting' ? 50 : 0)
    }))
  } catch (error) {
    console.error('获取生成任务失败:', error)
    ElMessage.error('获取生成任务列表失败')
  } finally {
    loading.value = false
  }
}

async function fetchTemplates() {
  try {
    const data = await templateApi.list()
    const templateList = data.records || data || []
    // 获取每个模板的来源文件
    templates.value = await Promise.all(templateList.map(async (t) => {
      try {
        const sourceFiles = await sourceFileApi.list(t.id)
        return { ...t, sourceFiles: sourceFiles || [] }
      } catch {
        return { ...t, sourceFiles: [] }
      }
    }))
  } catch (error) {
    console.error('获取模板列表失败:', error)
  }
}

const newGeneration = reactive({
  name: '',
  templateId: '',
  sourceFileMap: {}
})

const selectedTemplate = computed(() => {
  return templates.value.find(t => t.id === newGeneration.templateId)
})

const filteredGenerations = computed(() => {
  let result = generations.value

  if (statusFilter.value) {
    result = result.filter(g => g.status === statusFilter.value)
  }

  if (searchKeyword.value) {
    result = result.filter(g =>
      g.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  return result
})

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 viewGeneration(gen) {
  router.push(`/generations/${gen.id}`)
}

async function executeGeneration(gen) {
  try {
    gen.status = 'extracting'
    gen.progress = 0
    
    await generationApi.execute(gen.id)
    
    // 轮询进度
    const interval = setInterval(async () => {
      try {
        const progress = await generationApi.getProgress(gen.id)
        gen.progress = progress.progress || 0
        gen.status = progress.status
        if (progress.status === 'review' || progress.status === 'completed' || progress.status === 'error') {
          clearInterval(interval)
        }
      } catch {
        clearInterval(interval)
      }
    }, 2000)
    
    ElMessage.success('开始提取变量')
  } catch (error) {
    ElMessage.error('执行失败: ' + error.message)
    gen.status = 'error'
  }
}

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

function downloadGeneration(gen) {
  const url = generationApi.getDownloadUrl(gen.id)
  window.open(url, '_blank')
}

function handleSourceFileUpload(alias, response) {
  if (response.code === 200) {
    newGeneration.sourceFileMap[alias] = response.data.id
    ElMessage.success(`${alias} 上传成功`)
  }
}

async function createGeneration() {
  if (!newGeneration.templateId) {
    ElMessage.warning('请选择模板')
    return
  }

  // 检查必需文件
  const template = selectedTemplate.value
  const missingFiles = (template.sourceFiles || [])
    .filter(sf => sf.required && !newGeneration.sourceFileMap[sf.alias])
    .map(sf => sf.alias)

  if (missingFiles.length > 0) {
    ElMessage.warning(`请上传必需文件: ${missingFiles.join(', ')}`)
    return
  }

  creating.value = true
  try {
    const data = {
      templateId: newGeneration.templateId,
      name: newGeneration.name || template.name,
      sourceFileMap: newGeneration.sourceFileMap
    }
    
    const gen = await generationApi.create(data)
    
    // 添加到列表
    generations.value.unshift({
      ...gen,
      templateName: template.name,
      variableCount: 0,
      progress: 0
    })
    
    showCreateDialog.value = false
    ElMessage.success('生成任务创建成功')
    
    // 重置表单
    Object.assign(newGeneration, { name: '', templateId: '', sourceFileMap: {} })
  } catch (error) {
    ElMessage.error('创建失败: ' + error.message)
  } finally {
    creating.value = false
  }
}
</script>

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

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: center;
}

.generation-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.generation-card {
  padding: 18px;

  .gen-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 10px;

    .gen-icon {
      font-size: 22px;
    }

    .gen-name {
      flex: 1;
      font-size: 15px;
      font-weight: 600;
    }
  }

  .gen-meta {
    display: flex;
    gap: 20px;
    font-size: 12px;
    color: var(--text-2);
    margin-bottom: 12px;
  }

  .gen-progress {
    margin-bottom: 12px;
  }

  .gen-actions {
    display: flex;
    gap: 8px;
  }
}

.source-files-upload {
  .source-file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    background: var(--bg);
    border-radius: 6px;
    margin-bottom: 8px;

    .sf-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .sf-name {
        font-weight: 500;
      }
    }
  }
}
</style>
