<template>
  <div class="page-container">
    <div class="page-header">
      <span class="page-title">经验库</span>
      <div class="header-controls">
        <el-button type="success" size="small" @click="showImportDialog = true">
          <el-icon><Upload /></el-icon> 从方案导入
        </el-button>
        <el-button type="primary" size="small" @click="showSimilarDialog = true">
          <el-icon><Search /></el-icon> 相似检索
        </el-button>
        <el-button size="small" @click="loadAll">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- Stats Cards -->
    <el-row :gutter="16" class="stats-row" v-if="stats">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">案例总数</div>
          <div class="stat-value">{{ stats.total }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-primary">
          <div class="stat-label">SSSR / DRSS</div>
          <div class="stat-value">{{ stats.topology_distribution?.SSSR || 0 }}<span class="stat-sub"> / {{ stats.topology_distribution?.DRSS || 0 }}</span></div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-success">
          <div class="stat-label">平均评分</div>
          <div class="stat-value">{{ stats.avg_rating || 0 }}<span class="stat-sub">/5</span></div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">跟踪参数</div>
          <div class="stat-value">{{ Object.keys(stats.param_coverage || {}).length }}</div>
        </div>
      </el-col>
    </el-row>

    <!-- Filters -->
    <div class="card filter-bar">
      <el-input v-model="searchKeyword" placeholder="搜索结论或标签..." style="width: 280px" clearable @input="loadExperience" :prefix-icon="Search" />
      <el-select v-model="topologyFilter" placeholder="拓扑结构" style="width: 130px" clearable @change="loadExperience">
        <el-option label="SSSR" value="SSSR" />
        <el-option label="DRSS" value="DRSS" />
      </el-select>
      <el-select v-model="tagFilter" placeholder="标签" style="width: 150px" clearable @change="loadExperience">
        <el-option v-for="t in allTags" :key="t" :label="t" :value="t" />
      </el-select>
      <el-select v-model="minRating" placeholder="最低评分" style="width: 130px" clearable @change="loadExperience">
        <el-option label="1星" :value="1" />
        <el-option label="2星" :value="2" />
        <el-option label="3星" :value="3" />
        <el-option label="4星" :value="4" />
        <el-option label="5星" :value="5" />
      </el-select>
    </div>

    <!-- Table -->
    <div class="card">
      <el-table :data="filteredCases" v-loading="loading" stripe @row-click="openDetail" highlight-current-row>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="topology" label="拓扑" width="90">
          <template #default="{ row }">
            <el-tag size="small" :type="row.topology === 'SSSR' ? 'primary' : 'success'">{{ row.topology }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source_plan_id" label="来源方案" width="160" show-overflow-tooltip />
        <el-table-column label="关键参数" min-width="180">
          <template #default="{ row }">
            <span v-for="(v, k) in row.params" :key="k" class="param-chip">
              {{ k }}={{ v }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="指标" min-width="220">
          <template #default="{ row }">
            <div class="metrics-cell">
              <span class="metric-item"><strong>转矩:</strong> {{ row.metrics?.tavg_nm?.toFixed(3) }}Nm</span>
              <span class="metric-item"><strong>效率:</strong> {{ row.metrics?.efficiency_pct?.toFixed(1) }}%</span>
              <span class="metric-item"><strong>脉动:</strong> {{ row.metrics?.ripple_pct?.toFixed(2) }}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="conclusion" label="结论" min-width="180" show-overflow-tooltip />
        <el-table-column label="标签" width="120">
          <template #default="{ row }">
            <el-tag v-for="t in row.tags" :key="t" size="small" style="margin-right: 4px" type="info">{{ t }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="90">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template #default="{ row }">{{ formatDate(row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" text type="primary" @click.stop="openEdit(row)">编辑</el-button>
            <el-button size="small" text type="danger" @click.stop="deleteCase(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-info">共 {{ totalCases }} 条，显示 {{ filteredCases.length }} 条</div>
    </div>

    <!-- Detail Dialog -->
    <el-dialog v-model="detailVisible" :title="`经验案例 #${selectedCase?.id}`" width="700px">
      <div v-if="selectedCase" class="detail-content">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="拓扑">{{ selectedCase.topology }}</el-descriptions-item>
          <el-descriptions-item label="来源方案">{{ selectedCase.source_plan_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="模型路径" :span="2">{{ selectedCase.model_path || '-' }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate v-model="selectedCase.rating" disabled size="small" />
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedCase.created_at) }}</el-descriptions-item>
        </el-descriptions>

        <h4 class="detail-section">参数</h4>
        <el-table :data="paramRows" size="small" border>
          <el-table-column prop="key" label="Parameter" width="180" />
          <el-table-column prop="value" label="Value" />
        </el-table>

        <h4 class="detail-section">指标</h4>
        <el-table :data="metricRows" size="small" border>
          <el-table-column prop="key" label="Metric" width="180" />
          <el-table-column prop="value" label="Value" />
        </el-table>

        <h4 class="detail-section">结论</h4>
        <p class="conclusion-text">{{ selectedCase.conclusion || '暂无结论记录。' }}</p>

        <h4 class="detail-section" v-if="selectedCase.tags?.length">标签</h4>
        <el-tag v-for="t in selectedCase.tags" :key="t" style="margin-right: 6px">{{ t }}</el-tag>
      </div>
    </el-dialog>

    <!-- Edit Dialog -->
    <el-dialog v-model="editVisible" :title="`Edit Case #${editForm.id}`" width="600px">
      <el-form :model="editForm" label-width="120px" size="small">
        <el-form-item label="Topology">
          <el-select v-model="editForm.topology" style="width: 100%">
            <el-option label="SSSR" value="SSSR" />
            <el-option label="DRSS" value="DRSS" />
          </el-select>
        </el-form-item>
        <el-form-item label="Conclusion">
          <el-input v-model="editForm.conclusion" type="textarea" :rows="3" placeholder="Enter conclusion..." />
        </el-form-item>
        <el-form-item label="Tags">
          <el-select v-model="editForm.tags" multiple filterable allow-create style="width: 100%" placeholder="Add tags...">
            <el-option v-for="t in allTags" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="Rating">
          <el-rate v-model="editForm.rating" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">Cancel</el-button>
        <el-button type="primary" @click="saveEdit" :loading="editLoading">Save</el-button>
      </template>
    </el-dialog>

    <!-- Import Dialog -->
    <el-dialog v-model="showImportDialog" title="从方案导入经验库" width="500px">
      <el-form label-width="120px" size="small">
        <el-form-item label="选择方案" required>
          <el-select v-model="importPlanId" placeholder="请选择方案" style="width: 100%" filterable>
            <el-option v-for="p in allPlans" :key="p.id" :label="`${p.name} (${p.plan_id})`" :value="p.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="importTags" multiple filterable allow-create style="width: 100%" placeholder="添加标签...">
            <el-option label="auto-imported" value="auto-imported" />
            <el-option label="verified" value="verified" />
          </el-select>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate v-model="importRating" />
        </el-form-item>
        <el-form-item label="自动结论">
          <el-switch v-model="importAutoConclusion" />
          <span style="margin-left: 8px; font-size: 12px; color: #909399">根据指标自动生成结论</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="success" @click="doImport" :loading="importLoading" :disabled="!importPlanId">导入</el-button>
      </template>
    </el-dialog>

    <!-- Similar Case Search Dialog -->
    <el-dialog v-model="showSimilarDialog" title="相似案例检索" width="600px">
      <div class="similar-form">
        <p class="form-hint">输入参数值以检索相似经验案例，留空则忽略该参数。</p>
        <el-form label-width="140px" size="small">
          <el-form-item v-for="p in similarParams" :key="p.key" :label="p.key">
            <el-input v-model.number="p.value" type="number" placeholder="value" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="拓扑">
            <el-select v-model="similarTopology" placeholder="全部" clearable style="width: 200px">
              <el-option label="SSSR" value="SSSR" />
              <el-option label="DRSS" value="DRSS" />
            </el-select>
          </el-form-item>
          <el-form-item label="结果数量">
            <el-input-number v-model="similarTopK" :min="1" :max="20" style="width: 200px" />
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="searchSimilar" :loading="similarLoading">检索</el-button>
      </div>

      <div v-if="similarResults.length > 0" class="similar-results">
        <el-divider>检索结果 ({{ similarResults.length }})</el-divider>
        <el-table :data="similarResults" size="small" stripe @row-click="(row: any) => { selectedCase = row; detailVisible = true }">
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="topology" label="拓扑" width="70" />
          <el-table-column label="相似度" width="100">
            <template #default="{ row }">
              <el-progress :percentage="Math.round(row.similarity_score * 100)" :stroke-width="8" :color="row.similarity_score > 0.7 ? '#67c23a' : row.similarity_score > 0.5 ? '#e6a23c' : '#f56c6c'" />
            </template>
          </el-table-column>
          <el-table-column label="共享参数" min-width="150">
            <template #default="{ row }">
              <el-tag v-for="p in row.shared_params" :key="p" size="small" style="margin-right: 4px" type="info">{{ p }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="conclusion" label="结论" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Upload } from '@element-plus/icons-vue'
import { experienceApi, analyticsApi, planApi } from '@/api'

const loading = ref(false)
const cases = ref<any[]>([])
const totalCases = ref(0)
const stats = ref<any>(null)
const topologyFilter = ref('')
const tagFilter = ref('')
const searchKeyword = ref('')
const minRating = ref<number | null>(null)
const allTags = ref<string[]>([])

// Detail dialog
const detailVisible = ref(false)
const selectedCase = ref<any>(null)

// Similar search
const showSimilarDialog = ref(false)
const similarLoading = ref(false)
const similarResults = ref<any[]>([])
const similarTopology = ref('')
const similarTopK = ref(5)
const similarParams = reactive([
  { key: 'Airgap', value: null },
  { key: 'RMSCurrent', value: null },
  { key: 'MagnetThickness', value: null },
  { key: 'PolePairs', value: null },
  { key: 'OuterRadius', value: null },
  { key: 'InnerRadius', value: null },
  { key: 'Speed', value: null },
  { key: 'TurnsPerCoil', value: null }
])

// Edit dialog
const editVisible = ref(false)
const editLoading = ref(false)
const editForm = reactive<any>({
  id: null,
  topology: 'SSSR',
  conclusion: '',
  tags: [] as string[],
  rating: 0
})

// Import dialog
const showImportDialog = ref(false)
const importLoading = ref(false)
const importPlanId = ref<number | null>(null)
const importTags = ref<string[]>(['auto-imported'])
const importRating = ref(0)
const importAutoConclusion = ref(true)
const allPlans = ref<any[]>([])

const filteredCases = computed(() => {
  let result = cases.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    result = result.filter(c =>
      (c.conclusion || '').toLowerCase().includes(kw) ||
      (c.tags || []).some((t: string) => t.toLowerCase().includes(kw))
    )
  }
  if (tagFilter.value) {
    result = result.filter(c => (c.tags || []).includes(tagFilter.value))
  }
  if (minRating.value !== null) {
    result = result.filter(c => (c.rating || 0) >= minRating.value!)
  }
  return result
})

const paramRows = computed(() => {
  if (!selectedCase.value?.params) return []
  return Object.entries(selectedCase.value.params).map(([key, value]) => ({ key, value }))
})

const metricRows = computed(() => {
  if (!selectedCase.value?.metrics) return []
  return Object.entries(selectedCase.value.metrics).map(([key, value]) => ({ key, value }))
})

async function loadExperience() {
  loading.value = true
  try {
    const params: any = { limit: 200 }
    if (topologyFilter.value) params.topology = topologyFilter.value
    if (tagFilter.value) params.tag = tagFilter.value
    const res = await experienceApi.list(params)
    cases.value = res.data.items
    totalCases.value = res.data.total
    // Collect all tags
    const tags = new Set<string>()
    for (const c of cases.value) {
      for (const t of (c.tags || [])) tags.add(t)
    }
    allTags.value = Array.from(tags)
  } catch (e: any) {
    ElMessage.error('加载经验库失败：' + e.message)
  } finally {
    loading.value = false
  }
}

async function loadStats() {
  try {
    const res = await analyticsApi.experienceStats(topologyFilter.value || undefined)
    stats.value = res.data
  } catch (e: any) {
    console.error('Failed to load stats:', e)
  }
}

async function loadAll() {
  await Promise.all([loadExperience(), loadStats()])
}

function openDetail(row: any) {
  selectedCase.value = row
  detailVisible.value = true
}

function openEdit(row: any) {
  editForm.id = row.id
  editForm.topology = row.topology
  editForm.conclusion = row.conclusion || ''
  editForm.tags = [...(row.tags || [])]
  editForm.rating = row.rating || 0
  editVisible.value = true
}

async function saveEdit() {
  if (!editForm.id) return
  editLoading.value = true
  try {
    await experienceApi.update(editForm.id, {
      topology: editForm.topology,
      conclusion: editForm.conclusion,
      tags: editForm.tags,
      rating: editForm.rating
    })
    ElMessage.success('案例更新成功')
    editVisible.value = false
    await loadAll()
  } catch (e: any) {
    ElMessage.error('更新失败：' + e.message)
  } finally {
    editLoading.value = false
  }
}

async function deleteCase(row: any) {
  try {
    await ElMessageBox.confirm(`确定删除经验案例 #${row.id}？`, '确认删除', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    })
  } catch {
    return
  }
  try {
    await experienceApi.delete(row.id)
    ElMessage.success('案例已删除')
    await loadAll()
  } catch (e: any) {
    ElMessage.error('Delete failed: ' + e.message)
  }
}

async function loadPlans() {
  try {
    const res = await planApi.list({ limit: 100 })
    allPlans.value = res.data.items || []
  } catch (e: any) {
    console.error('Failed to load plans:', e)
  }
}

async function doImport() {
  if (!importPlanId.value) return
  importLoading.value = true
  try {
    const res = await experienceApi.importFromPlan(importPlanId.value, {
      tags: importTags.value,
      rating: importRating.value,
      auto_conclusion: importAutoConclusion.value
    })
    ElMessage.success(`Imported ${res.data.imported} cases (skipped ${res.data.skipped})`)
    showImportDialog.value = false
    importPlanId.value = null
    await loadAll()
  } catch (e: any) {
    ElMessage.error('Import failed: ' + e.message)
  } finally {
    importLoading.value = false
  }
}

async function searchSimilar() {
  const params: Record<string, number> = {}
  for (const p of similarParams) {
    if (p.value !== null && p.value !== undefined && p.value !== '') {
      params[p.key] = p.value
    }
  }
  if (Object.keys(params).length === 0) {
    ElMessage.warning('请至少输入一个参数值')
    return
  }
  similarLoading.value = true
  try {
    const res = await analyticsApi.experienceSimilar(params, similarTopology.value || undefined, similarTopK.value)
    similarResults.value = res.data.items
    if (similarResults.value.length === 0) {
      ElMessage.info('未找到相似案例，请调整参数或容差。')
    }
  } catch (e: any) {
    ElMessage.error('检索失败：' + e.message)
  } finally {
    similarLoading.value = false
  }
}

function formatDate(d: string) {
  return new Date(d).toLocaleString()
}

onMounted(() => {
  loadAll()
  loadPlans()
})
</script>

<style scoped>
.page-container {
  padding: 20px 24px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
}
.header-controls {
  display: flex;
  gap: 8px;
}
.stats-row {
  margin-bottom: 16px;
}
.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 14px 18px;
  border: 1px solid #e2e8f0;
}
.stat-label {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 4px;
}
.stat-value {
  font-size: 22px;
  font-weight: 700;
  color: #1e293b;
}
.stat-sub {
  font-size: 13px;
  font-weight: 400;
  color: #94a3b8;
}
.stat-success .stat-value { color: #16a34a; }
.stat-primary .stat-value { color: #2563eb; }
.filter-bar {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
}
.card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e2e8f0;
  margin-bottom: 16px;
}
.param-chip {
  display: inline-block;
  font-size: 11px;
  background: #f1f5f9;
  color: #475569;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 6px;
  margin-bottom: 2px;
}
.metrics-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.metric-item {
  font-size: 12px;
  color: #475569;
}
.pagination-info {
  margin-top: 12px;
  font-size: 12px;
  color: #94a3b8;
  text-align: right;
}
.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}
.detail-section {
  margin: 16px 0 8px;
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}
.conclusion-text {
  background: #f8fafc;
  padding: 12px;
  border-radius: 6px;
  font-size: 13px;
  line-height: 1.6;
  color: #475569;
}
.similar-form {
  margin-bottom: 16px;
}
.form-hint {
  font-size: 12px;
  color: #94a3b8;
  margin-bottom: 12px;
}
.similar-results {
  margin-top: 8px;
}
</style>
