<template>
  <div class="fidelity-calibration">
    <el-row :gutter="20">
      <el-col :span="10">
        <el-card shadow="never">
          <template #header><span class="title">\u591a\u4fdd\u771f\u5ea6\u7ed3\u679c\u6821\u51c6</span></template>
          <el-form :model="form" label-width="120px" size="default">
            <el-form-item label="\u6307\u6807\u540d\u79f0">
              <el-select v-model="form.metric" filterable allow-create>
                <el-option label="\u5e73\u5747\u8f6c\u77e9 (tavg_nm)" value="tavg_nm" />
                <el-option label="\u6548\u7387 (efficiency_pct)" value="efficiency_pct" />
                <el-option label="\u603b\u635f\u8017 (total_losses_w)" value="total_losses_w" />
                <el-option label="\u7ed5\u7ec4\u6e29\u5ea6 (winding_temp_c)" value="winding_temp_c" />
              </el-select>
            </el-form-item>
            <el-form-item label="\u4fdd\u771f\u5ea6\u7b49\u7ea7">
              <el-select v-model="form.fidelity">
                <el-option v-for="(info, key) in fidelityLevels" :key="key" :label="`${key} - ${info.name}`" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="\u539f\u59cb\u503c">
              <el-input-number v-model="form.value" :precision="4" controls-position="right" style="width: 100%;" />
            </el-form-item>
            <el-button type="primary" style="width: 100%;" :loading="calibrating" @click="doCalibrate">
              \u6267\u884c\u6821\u51c6
            </el-button>
          </el-form>
        </el-card>

        <el-card v-if="result" shadow="never" style="margin-top: 20px;">
          <template #header><span>\u6821\u51c6\u7ed3\u679c</span></template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="\u539f\u59cb\u503c">{{ result.raw_value }}</el-descriptions-item>
            <el-descriptions-item label="\u4fdd\u771f\u5ea6">{{ result.fidelity }}</el-descriptions-item>
            <el-descriptions-item label="\u6821\u51c6\u540e\u503c">
              <span style="font-weight: 700; color: #67c23a; font-size: 18px;">{{ result.calibrated_value }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="\u6821\u51c6\u56e0\u5b50">{{ result.correction_factor }}</el-descriptions-item>
            <el-descriptions-item label="\u4e0d\u786e\u5b9a\u5ea6">\u00b1{{ result.uncertainty_pct }}% (\u00b1{{ result.uncertainty_abs }})</el-descriptions-item>
          </el-descriptions>
          <el-progress
            v-if="result.calibrated"
            :percentage="Math.round((1 - 1 / result.correction_factor) * 100)"
            :status="result.correction_factor > 1 ? 'success' : 'warning'"
            style="margin-top: 12px;"
          />
        </el-card>
      </el-col>

      <el-col :span="14">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>\u4fdd\u771f\u5ea6\u7b49\u7ea7\u5b9a\u4e49</span>
              <el-tag type="info" size="small">L0 \u2192 L4</el-tag>
            </div>
          </template>
          <el-table :data="fidelityTable" border size="small">
            <el-table-column prop="level" label="\u7b49\u7ea7" width="80" />
            <el-table-column prop="name" label="\u540d\u79f0" width="200" />
            <el-table-column prop="bias" label="\u504f\u5dee(%)" width="100" />
            <el-table-column prop="cost" label="\u8ba1\u7b97\u6210\u672c" width="120" />
            <el-table-column prop="description" label="\u8bf4\u660e" />
          </el-table>
        </el-card>

        <el-card shadow="never" style="margin-top: 20px;">
          <template #header><span>\u6821\u51c6\u56e0\u5b50\u7ba1\u7406</span></template>
          <el-form :inline="true" size="small">
            <el-form-item label="\u4f4e\u4fdd\u771f\u5ea6">
              <el-select v-model="updateForm.low_fidelity" style="width: 100px;">
                <el-option v-for="(info, key) in fidelityLevels" :key="key" :label="key" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="\u9ad8\u4fdd\u771f\u5ea6">
              <el-select v-model="updateForm.high_fidelity" style="width: 100px;">
                <el-option label="L4" value="L4" />
              </el-select>
            </el-form-item>
            <el-form-item label="\u4f4e\u4fdd\u771f\u503c">
              <el-input-number v-model="updateForm.low_value" :precision="4" />
            </el-form-item>
            <el-form-item label="\u9ad8\u4fdd\u771f\u503c">
              <el-input-number v-model="updateForm.high_value" :precision="4" />
            </el-form-item>
            <el-button type="primary" @click="updateCalibration">\u66f4\u65b0\u6821\u51c6\u56e0\u5b50</el-button>
          </el-form>
          <el-alert title="\u6821\u51c6\u56e0\u5b50\u91c7\u7528\u6307\u6570\u79fb\u52a8\u5e73\u5747(EMA)\u66f4\u65b0\uff0c\u65b0\u6570\u636e\u6743\u91cd30%\uff0c\u65e7\u6570\u636e\u6743\u91cd70%" type="info" :closable="false" show-icon style="margin-top: 12px;" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

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

const form = reactive({ metric: 'tavg_nm', fidelity: 'L2', value: 10 })
const result = ref<any>(null)
const calibrating = ref(false)

const updateForm = reactive({
  low_fidelity: 'L2', high_fidelity: 'L4',
  low_value: 9.5, high_value: 10.0,
})

const fidelityLevels: Record<string, any> = {
  L0: { name: '\u89e3\u6790\u9884\u7b5b\u9009', bias_pct: 20, cost: 0.01 },
  L1: { name: '\u78c1\u8def\u7b49\u6548\u7535\u8def', bias_pct: 15, cost: 0.1 },
  L2: { name: '2D FEA (Maxwell)', bias_pct: 8, cost: 1 },
  L3: { name: '3D FEA (Motor-CAD)', bias_pct: 3, cost: 5 },
  L4: { name: '3D\u77ac\u6001+\u70ed\u8026\u5408', bias_pct: 1, cost: 20 },
}

const fidelityTable = computed(() =>
  Object.entries(fidelityLevels).map(([level, info]: any) => ({
    level, name: info.name, bias: info.bias_pct, cost: `${info.cost}x`,
    description: level === 'L4' ? '\u53c2\u8003\u57fa\u51c6\uff0c\u65e0\u9700\u6821\u51c6' : `\u504f\u5dee\u7ea6${info.bias_pct}%\uff0c\u9700\u6821\u51c6\u5230L4`,
  }))
)

const doCalibrate = async () => {
  calibrating.value = true
  try {
    result.value = await analysisApi.calibrate({ ...form })
  } catch (e: any) {
    ElMessage.error('\u6821\u51c6\u5931\u8d25: ' + (e.message || e))
  } finally {
    calibrating.value = false
  }
}

const updateCalibration = async () => {
  try {
    await analysisApi.updateCalibration({
      low_fidelity_results: { [form.metric]: updateForm.low_value },
      high_fidelity_results: { [form.metric]: updateForm.high_value },
      low_fidelity: updateForm.low_fidelity,
      high_fidelity: updateForm.high_fidelity,
    })
    ElMessage.success('\u6821\u51c6\u56e0\u5b50\u5df2\u66f4\u65b0')
  } catch (e: any) {
    ElMessage.error('\u66f4\u65b0\u5931\u8d25: ' + (e.message || e))
  }
}
</script>

<style scoped>
.fidelity-calibration { padding: 20px; }
.title { font-weight: 600; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
</style>
