<template>
  <div class="experience-enhance">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">\u7ecf\u9a8c\u5e93 AI \u589e\u5f3a</span>
          <el-tag type="info" size="small">AI\u63d0\u53d6\u8bbe\u8ba1\u77e5\u8bc6</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form label-width="100px" size="small">
            <el-form-item label="\u9879\u76ee\u540d\u79f0">
              <el-input v-model="projectName" placeholder="\u5982: MARS-12S10P \u4f18\u5316" />
            </el-form-item>
            <el-form-item label="\u62d3\u6251">
              <el-select v-model="topology">
                <el-option label="SSSR" value="SSSR" />
                <el-option label="DRSS" value="DRSS" />
                <el-option label="SDSR" value="SDSR" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="input-label">\u4eff\u771f\u7ed3\u679c\u6570\u636e</div>
          <el-input v-model="resultsJson" type="textarea" :rows="8" placeholder="JSON\u6570\u7ec4\u683c\u5f0f\u7684\u4eff\u771f\u7ed3\u679c..." />
          <div class="actions">
            <el-button size="small" @click="loadExample">\u52a0\u8f7d\u793a\u4f8b</el-button>
            <el-button type="primary" :loading="extracting" @click="doExtract">
              <el-icon><MagicStick /></el-icon> AI\u63d0\u53d6\u77e5\u8bc6
            </el-button>
          </div>
        </el-col>

        <el-col :span="16">
          <div v-if="!insights" class="empty-state">
            <el-empty description="\u8f93\u5165\u4eff\u771f\u7ed3\u679c\u540e\u70b9\u51fbAI\u63d0\u53d6\uff0c\u81ea\u52a8\u751f\u6210\u8bbe\u8ba1\u89c4\u5219\u3001\u5931\u8d25\u6a21\u5f0f\u548c\u53c2\u6570\u654f\u611f\u6027" />
          </div>
          <template v-else>
            <el-alert :title="insights.summary" type="success" :closable="false" show-icon style="margin-bottom: 16px;" />
            <el-row :gutter="16">
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-val">{{ insights.n_results_analyzed || '-' }}</div>
                  <div class="stat-label">\u5206\u6790\u70b9\u6570</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-val">{{ (insights.feasibility_rate * 100).toFixed(0) }}%</div>
                  <div class="stat-label">\u53ef\u884c\u7387</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-val">{{ insights.ai_used ? 'AI' : '\u542f\u53d1\u5f0f' }}</div>
                  <div class="stat-label">\u5206\u6790\u65b9\u5f0f</div>
                </div>
              </el-col>
            </el-row>

            <el-divider content-position="left">\u8bbe\u8ba1\u89c4\u5219</el-divider>
            <el-timeline v-if="insights.design_rules?.length">
              <el-timeline-item v-for="(rule, idx) in insights.design_rules" :key="idx" type="primary" placement="top">
                {{ rule }}
              </el-timeline-item>
            </el-timeline>
            <el-empty v-else description="\u672a\u63d0\u53d6\u5230\u8bbe\u8ba1\u89c4\u5219" :image-size="60" />

            <el-divider v-if="insights.failure_patterns?.length" content-position="left">\u5931\u8d25\u6a21\u5f0f</el-divider>
            <el-alert v-for="(pattern, idx) in insights.failure_patterns" :key="idx" :title="pattern" type="warning" :closable="false" show-icon style="margin-bottom: 8px;" />

            <div class="actions" style="margin-top: 20px;">
              <el-button type="success" @click="saveToExperience">
                <el-icon><Upload /></el-icon> \u5ba1\u6838\u5165\u5e93
              </el-button>
              <el-button @click="insights = null">\u91cd\u65b0\u63d0\u53d6</el-button>
            </div>
          </template>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { MagicStick, Upload } from '@element-plus/icons-vue'
import { adaptiveApi } from '@/api/ai'

const projectName = ref('')
const topology = ref('SSSR')
const resultsJson = ref('')
const extracting = ref(false)
const insights = ref<any>(null)

const loadExample = () => {
  const data = []
  for (let i = 0; i < 20; i++) {
    const airgap = 0.5 + Math.random() * 1.5
    const magnet = 3 + Math.random() * 5
    data.push({
      airgap_mm: +airgap.toFixed(2),
      magnet_thickness_mm: +magnet.toFixed(1),
      tavg_nm: +(magnet * 2 / Math.sqrt(airgap) + (Math.random() - 0.5)).toFixed(2),
      efficiency_pct: +(85 + Math.random() * 8).toFixed(1),
      feasible: airgap > 0.6 && magnet > 3.5,
    })
  }
  resultsJson.value = JSON.stringify(data, null, 2)
  projectName.value = 'SSSR \u6c14\u9699-\u78c1\u94a2\u539a\u5ea6\u4f18\u5316'
}

const doExtract = async () => {
  let results: any[]
  try {
    results = JSON.parse(resultsJson.value)
  } catch {
    ElMessage.error('\u7ed3\u679c\u6570\u636e\u4e0d\u662f\u6709\u6548\u7684JSON')
    return
  }
  if (!Array.isArray(results) || results.length < 5) {
    ElMessage.warning('\u81f3\u5c11\u9700\u89815\u6761\u7ed3\u679c\u624d\u80fd\u63d0\u53d6\u7ecf\u9a8c')
    return
  }
  extracting.value = true
  try {
    const requirement = `\u9879\u76ee: ${projectName.value || '\u672a\u547d\u540d'}, \u62d3\u6251: ${topology.value}. \u8bf7\u4ece\u4ee5\u4e0b\u4eff\u771f\u7ed3\u679c\u4e2d\u63d0\u53d6\u8bbe\u8ba1\u7ecf\u9a8c: ${JSON.stringify(results.slice(0, 50))}`
    const res: any = await adaptiveApi.createLoop({ user_requirement: requirement, total_budget: 10 })
    const loopId = res.loop_id
    await adaptiveApi.generatePlan(loopId)
    const expRes: any = await adaptiveApi.updateExperience(loopId)
    insights.value = expRes.insights || expRes
    ElMessage.success('\u77e5\u8bc6\u63d0\u53d6\u5b8c\u6210')
  } catch (e: any) {
    ElMessage.error('\u63d0\u53d6\u5931\u8d25: ' + (e.message || e))
  } finally {
    extracting.value = false
  }
}

const saveToExperience = () => {
  ElMessage.success('\u5df2\u63d0\u4ea4\u5ba1\u6838\uff0c\u5ba1\u6838\u901a\u8fc7\u540e\u5c06\u5165\u5e93\uff08\u5f00\u53d1\u4e2d\uff09')
}
</script>

<style scoped>
.experience-enhance { padding: 20px; }
.title { font-weight: 600; font-size: 16px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.input-label { font-weight: 600; color: #606266; font-size: 13px; margin: 12px 0 6px; }
.actions { margin-top: 12px; display: flex; gap: 10px; }
.empty-state { padding: 60px 0; }
.stat-box { text-align: center; padding: 16px; background: #f5f7fa; border-radius: 8px; }
.stat-val { font-size: 24px; font-weight: 700; color: #409eff; }
.stat-label { font-size: 12px; color: #909399; margin-top: 4px; }
</style>
