<template>
  <div class="template-detail-page">
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="router.back()">返回</el-button>
        <h1>{{ template?.name || '模板详情' }}</h1>
        <el-tag :type="getStatusType(template?.status)">
          {{ getStatusLabel(template?.status) }}
        </el-tag>
      </div>
      <div class="header-right">
        <el-button @click="router.push(`/editor/${templateId}`)">编辑模板</el-button>
        <el-button type="primary" @click="useTemplate">使用模板</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 基本信息 -->
        <div class="card section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="模板名称">{{ template?.name }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ getStatusLabel(template?.status) }}</el-descriptions-item>
            <el-descriptions-item label="使用次数">{{ template?.useCount || 0 }} 次</el-descriptions-item>
            <el-descriptions-item label="是否公开">{{ template?.isPublic ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="2">{{ template?.createTime }}</el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ template?.description || '暂无描述' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 变量列表 -->
        <div class="card section">
          <div class="section-header">
            <h3>变量列表 ({{ variables.length }})</h3>
          </div>
          <el-table :data="variables" stripe>
            <el-table-column prop="displayName" label="显示名称" width="150" />
            <el-table-column prop="name" label="变量名" width="150" />
            <el-table-column prop="category" label="类别" width="120">
              <template #default="{ row }">
                <el-tag :color="getCategoryColor(row.category)" effect="dark" size="small">
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sourceType" label="来源类型" width="120">
              <template #default="{ row }">
                {{ getSourceTypeLabel(row.sourceType) }}
              </template>
            </el-table-column>
            <el-table-column prop="exampleValue" label="示例值" />
          </el-table>
        </div>
      </el-col>

      <el-col :span="8">
        <!-- 来源文件定义 -->
        <div class="card section">
          <h3>来源文件定义 ({{ sourceFiles.length }})</h3>
          <div class="source-file-list">
            <div v-for="sf in sourceFiles" :key="sf.id" class="source-file-item">
              <span class="sf-icon">📄</span>
              <div class="sf-info">
                <div class="sf-name">{{ sf.alias }}</div>
                <div class="sf-desc">{{ sf.description || '暂无描述' }}</div>
              </div>
              <el-tag size="small" :type="sf.required ? 'danger' : 'info'">
                {{ sf.required ? '必需' : '可选' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="card section">
          <h3>统计信息</h3>
          <div class="stat-item">
            <span class="stat-label">变量总数</span>
            <span class="stat-value">{{ variables.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">来源文件</span>
            <span class="stat-value">{{ sourceFiles.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">生成次数</span>
            <span class="stat-value">{{ template?.useCount || 0 }}</span>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

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

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

const loading = ref(false)

// 从 API 获取数据
const template = ref(null)
const sourceFiles = ref([])
const variables = ref([])

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

async function fetchTemplateDetail() {
  loading.value = true
  try {
    // 并行获取模板详情、来源文件和变量
    const [templateData, sourceFilesData, variablesData] = await Promise.all([
      templateApi.getById(templateId),
      sourceFileApi.list(templateId),
      variableApi.list(templateId)
    ])
    
    template.value = templateData
    sourceFiles.value = sourceFilesData || []
    variables.value = variablesData || []
  } catch (error) {
    console.error('获取模板详情失败:', error)
    ElMessage.error('获取模板详情失败')
  } finally {
    loading.value = false
  }
}

function getStatusType(status) {
  const map = { draft: 'info', published: 'success', archived: 'warning' }
  return map[status] || 'info'
}

function getStatusLabel(status) {
  const map = { draft: '草稿', published: '已发布', archived: '已归档' }
  return map[status] || status
}

function getCategoryColor(category) {
  const map = {
    entity: '#1890ff',
    concept: '#722ed1',
    data: '#52c41a',
    location: '#faad14',
    asset: '#eb2f96'
  }
  return map[category] || '#8c8c8c'
}

function getCategoryLabel(category) {
  const map = {
    entity: '核心实体',
    concept: '概念/技术',
    data: '数据/指标',
    location: '地点/组织',
    asset: '资源模板'
  }
  return map[category] || '其他'
}

function getSourceTypeLabel(type) {
  const map = {
    document: '文档提取',
    manual: '手动输入',
    reference: '引用变量',
    fixed: '固定值'
  }
  return map[type] || type
}

function useTemplate() {
  router.push(`/generations?templateId=${templateId}`)
  ElMessage.info('请上传来源文件后开始生成')
}
</script>

<style lang="scss" scoped>
.template-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;
    }
  }
}

.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-desc {
        font-size: 12px;
        color: var(--text-3);
      }
    }
  }
}

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

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

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

  .stat-value {
    font-weight: 600;
  }
}
</style>
