<template>
  <div class="result-analysis">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">AI \u7ed3\u679c\u5206\u6790</span>
          <el-tag type="info" size="small">Kimi k3 + \u591a\u4fdd\u771f\u5ea6\u6821\u51c6</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form label-width="100px" size="small">
            <el-form-item label="\u4fdd\u771f\u5ea6\u7b49\u7ea7">
              <el-select v-model="fidelity">
                <el-option label="L0 - \u89e3\u6790\u9884\u7b5b\u9009" value="L0" />
                <el-option label="L1 - \u78c1\u8def\u7b49\u6548\u7535\u8def" value="L1" />
                <el-option label="L2 - 2D FEA" value="L2" />
                <el-option label="L3 - 3D FEA (Motor-CAD)" value="L3" />
                <el-option label="L4 - 3D\u77ac\u6001+\u70ed\u8026\u5408" value="L4" />
              </el-select>
            </el-form-item>
            <el-form-item label="\u76ee\u6807\u8f6c\u77e9">
              <el-input-number v-model="targets.tavg_nm" :min="0" />
            </el-form-item>
            <el-form-item label="\u76ee\u6807\u6548\u7387">
              <el-input-number v-model="targets.efficiency_pct" :min="0" :max="100" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <div class="input-area">
            <div class="input-label">\u4eff\u771f\u7ed3\u679c\u6570\u636e (JSON\u6570\u7ec4)</div>
            <el-input
              v-model="resultsJson"
              type="textarea"
              :rows="6"
              placeholder='[{"tavg_nm": 15.2, "efficiency_pct": 92.5, "airgap_mm": 1.0, ...}]'
            />
            <div class="actions">
              <el-button size="small" @click="loadExample">\u52a0\u8f7d\u793a\u4f8b</el-button>
              <el-button type="primary" :loading="analyzing" @click="doAnalyze">\u5f00\u59cb\u5206\u6790</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card v-if="analysis" shadow="never" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>\u5206\u6790\u7ed3\u679c</span>
          <ConfidenceBadge v-if="confidence" :grade="confidence.grade" :score="confidence.score" />
        </div>
      </template>
      <el-alert :title="analysis.summary" type="info" :closable="false" show-icon style="margin-bottom: 16px;" />
      <el-row :gutter="16">
        <el-col :span="12">
          <div class="section-title">\u5173\u952e\u6307\u6807\u7edf\u8ba1</div>
          <el-table :data="metricStats" border size="small">
            <el-table-column prop="metric" label="\u6307\u6807" width="140" />
            <el-table-column prop="min" label="\u6700\u5c0f" />
            <el-table-column prop="max" label="\u6700\u5927" />
            <el-table-column prop="mean" label="\u5747\u503c" />
          </el-table>
        </el-col>
        <el-col :span="12">
          <div class="section-title">\u6536\u655b\u6027\u68c0\u67e5</div>
          <el-table :data="convChecks" border size="small">
            <el-table-column prop="name" label="\u5224\u636e" width="160" />
            <el-table-column label="\u7ed3\u679c" width="80">
              <template #default="{ row }">
                <el-tag :type="row.passed ? 'success' : 'danger'" size="small">{{ row.passed ? 'PASS' : 'FAIL' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="\u6570\u503c" />
          </el-table>
        </el-col>
      </el-row>
      <el-divider v-if="aiAnalysis" content-position="left">AI \u6df1\u5ea6\u5206\u6790</el-divider>
      <el-descriptions v-if="aiAnalysis" :column="1" border size="small">
        <el-descriptions-item v-if="aiAnalysis.trend_analysis" label="\u8d8b\u52bf\u5206\u6790">{{ aiAnalysis.trend_analysis }}</el-descriptions-item>
        <el-descriptions-item v-if="aiAnalysis.recommendation" label="\u4f18\u5316\u5efa\u8bae">{{ aiAnalysis.recommendation }}</el-descriptions-item>
      </el-descriptions>
      <div v-if="aiAnalysis?.optimization_suggestions?.length" class="suggestions">
        <div class="section-title">\u4f18\u5316\u5efa\u8bae\u6e05\u5355</div>
        <el-timeline>
          <el-timeline-item
            v-for="(s, idx) in aiAnalysis.optimization_suggestions"
            :key="idx"
            :type="s.priority === 'high' ? 'danger' : s.priority === 'medium' ? 'warning' : 'primary'"
          >
            <strong>{{ s.suggestion }}</strong>
            <div v-if="s.expected_improvement" style="color: #909399; font-size: 12px;">\u9884\u671f\u6539\u5584: {{ s.expected_improvement }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { analysisApi } from '@/api/ai'
import ConfidenceBadge from '@/components/ai/ConfidenceBadge.vue'

const fidelity = ref('L3')
const targets = reactive({ tavg_nm: 10, efficiency_pct: 92 })
const resultsJson = ref('')
const analyzing = ref(false)
const analysis = ref<any>(null)
const aiAnalysis = ref<any>(null)

const confidence = computed(() => analysis.value?.confidence)
const metricStats = computed(() => {
  const stats = analysis.value?.quantitative?.statistics || {}
  return Object.entries(stats).map(([metric, s]: any) => ({
    metric, min: s.min, max: s.max, mean: s.mean,
  }))
})
const convChecks = computed(() => {
  const conv = analysis.value?.quantitative?.convergence || {}
  return Object.entries(conv)
    .filter(([k]) => k !== 'summary')
    .map(([name, v]: any) => ({ name, passed: v.passed, value: v.value ?? '-' }))
})

const loadExample = () => {
  const data = []
  for (let i = 0; i < 15; i++) {
    const airgap = 0.5 + Math.random() * 1.5
    const current = 10 + Math.random() * 15
    data.push({
      airgap_mm: +airgap.toFixed(2),
      current_a: +current.toFixed(1),
      tavg_nm: +(current * 2.5 / Math.sqrt(airgap) + (Math.random() - 0.5)).toFixed(2),
      efficiency_pct: +(88 + Math.random() * 5).toFixed(1),
      total_losses_w: +(40 + Math.random() * 20).toFixed(1),
      winding_temp_c: +(85 + Math.random() * 25).toFixed(1),
      feasible: Math.random() > 0.15,
    })
  }
  resultsJson.value = JSON.stringify(data, null, 2)
}

const doAnalyze = 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) {
    ElMessage.error('\u8bf7\u8f93\u5165\u81f3\u5c11\u4e00\u6761\u7ed3\u679c\u6570\u636e')
    return
  }
  analyzing.value = true
  try {
    const res: any = await analysisApi.analyze({
      results,
      targets: { ...targets },
      fidelity: fidelity.value,
    })
    analysis.value = res
    aiAnalysis.value = res.ai_analysis
    ElMessage.success('\u5206\u6790\u5b8c\u6210')
  } catch (e: any) {
    ElMessage.error('\u5206\u6790\u5931\u8d25: ' + (e.message || e))
  } finally {
    analyzing.value = false
  }
}
</script>

<style scoped>
.result-analysis { padding: 20px; }
.title { font-weight: 600; font-size: 16px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.input-area { display: flex; flex-direction: column; gap: 8px; }
.input-label { font-weight: 600; color: #606266; font-size: 13px; }
.actions { display: flex; gap: 8px; justify-content: flex-end; }
.section-title { font-weight: 600; margin: 12px 0 8px; color: #303133; }
.suggestions { margin-top: 16px; }
</style>
