<template>
  <div class="question-manage">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-left">
        <h2>问答管理</h2>
        <p class="header-desc">管理和生成问答数据</p>
      </div>
      <el-button type="primary" @click="showGenerateDialog = true" class="generate-btn">
        <el-icon><Plus /></el-icon>
        生成问题
      </el-button>
    </div>

    <!-- Stats -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon violet">
          <el-icon><ChatDotSquare /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ questions.length }}</span>
          <span class="stat-label">总问题数</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon cyan">
          <el-icon><MagicStick /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ generatedCount }}</span>
          <span class="stat-label">AI 生成</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon orange">
          <el-icon><EditPen /></el-icon>
        </div>
        <div class="stat-info">
          <span class="stat-value">{{ manualCount }}</span>
          <span class="stat-label">手动添加</span>
        </div>
      </div>
    </div>

    <!-- Question Table -->
    <div class="table-card">
      <el-table :data="questions" v-loading="loading" style="width: 100%">
        <el-table-column prop="content" label="问题内容" min-width="300">
          <template #default="{ row }">
            <div class="question-content">{{ row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案" min-width="200">
          <template #default="{ row }">
            <div class="answer-content">{{ row.answer || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="question_type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getTypeColor(row.question_type)" effect="dark">
              {{ getTypeName(row.question_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-popconfirm title="确定删除此问题？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" size="small" text>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Generate Dialog -->
    <el-dialog v-model="showGenerateDialog" title="生成问题" width="560px" class="generate-dialog">
      <el-form :model="generateConfig" label-position="top">
        <el-form-item label="选择文本块">
          <el-select
            v-model="generateConfig.chunk_ids"
            multiple
            placeholder="选择文本块"
            style="width: 100%"
            size="large"
          >
            <el-option
              v-for="chunk in chunks"
              :key="chunk.id"
              :label="chunk.name || chunk.content.slice(0, 50) + '...'"
              :value="chunk.id"
            />
          </el-select>
        </el-form-item>
        <div class="form-row">
          <el-form-item label="每个块生成数量">
            <el-input-number v-model="generateConfig.count" :min="1" :max="50" size="large" style="width: 100%" />
          </el-form-item>
        </div>
        <el-form-item label="问题类型">
          <el-checkbox-group v-model="generateConfig.question_types">
            <el-checkbox label="fact">事实性</el-checkbox>
            <el-checkbox label="summary">总结性</el-checkbox>
            <el-checkbox label="reasoning">推理性</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showGenerateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleGenerate" :loading="generating">开始生成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { chunkApi, questionApi } from '@/api'

const route = useRoute()
const projectId = computed(() => route.params.id)

const loading = ref(false)
const generating = ref(false)
const questions = ref([])
const chunks = ref([])
const showGenerateDialog = ref(false)

const generateConfig = reactive({
  chunk_ids: [],
  count: 5,
  question_types: ['fact', 'summary']
})

const generatedCount = computed(() => questions.value.filter(q => q.source === 'generated').length)
const manualCount = computed(() => questions.value.filter(q => q.source === 'manual').length)

const fetchQuestions = async () => {
  loading.value = true
  try {
    const res = await chunkApi.list(projectId.value, {})
    chunks.value = res.data.chunks || []
    questions.value = chunks.value.flatMap(c => (c.questions || []).map(q => ({ ...q, source: c.name })))
  } catch (error) {
    questions.value = []
  } finally {
    loading.value = false
  }
}

const handleGenerate = async () => {
  if (generateConfig.chunk_ids.length === 0) {
    ElMessage.warning('请选择文本块')
    return
  }
  generating.value = true
  try {
    await questionApi.generate(projectId.value, generateConfig)
    ElMessage.success('问题生成任务已启动')
    showGenerateDialog.value = false
    setTimeout(fetchQuestions, 2000)
  } catch (error) {
    ElMessage.error('生成失败')
  } finally {
    generating.value = false
  }
}

const handleDelete = async (question) => {
  try {
    await questionApi.delete(projectId.value, question.id)
    ElMessage.success('删除成功')
    fetchQuestions()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const getTypeColor = (type) => {
  const map = { 'fact': 'success', 'summary': 'primary', 'reasoning': 'warning' }
  return map[type] || 'info'
}

const getTypeName = (type) => {
  const map = { 'fact': '事实性', 'summary': '总结性', 'reasoning': '推理性' }
  return map[type] || type
}

onMounted(() => fetchQuestions())
</script>

<style scoped>
.question-manage {
  padding: 32px;
  max-width: 1200px;
}

/* Header */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
}

.header-left h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.header-desc {
  font-size: 14px;
  color: var(--text-tertiary);
}

.generate-btn {
  padding: 10px 20px;
  font-weight: 500;
  border-radius: var(--radius-md);
}

/* Stats Grid */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  font-size: 22px;
}

.stat-icon.violet { background: rgba(124, 58, 237, 0.15); color: var(--accent-secondary); }
.stat-icon.cyan { background: var(--accent-primary-muted); color: var(--accent-primary); }
.stat-icon.orange { background: rgba(251, 191, 36, 0.15); color: var(--warning); }

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
}

.stat-label {
  font-size: 13px;
  color: var(--text-tertiary);
}

/* Table Card */
.table-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  overflow: hidden;
}

.question-content {
  font-size: 14px;
  color: var(--text-primary);
  line-height: 1.5;
}

.answer-content {
  font-size: 13px;
  color: var(--text-tertiary);
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Form */
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.generate-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-secondary);
}

/* Responsive */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }
}
</style>
