<template>
  <div class="page-container" v-loading="loading">
    <div class="page-header">
      <div>
        <el-button text @click="goBack" style="padding: 0; margin-bottom: 8px">
          <el-icon><ArrowLeft /></el-icon> 返回
        </el-button>
        <span class="page-title">{{ plan?.name }}</span>
        <el-tag size="small" type="primary" style="margin-left: 12px">{{ plan?.plan_id }}</el-tag>
        <el-tag size="small" :type="planStatusType(plan?.status)" style="margin-left: 8px">{{ plan?.status }}</el-tag>
      </div>
      <div>
        <el-button @click="downloadPlan">
          <el-icon><Download /></el-icon> 下载JSON
        </el-button>
        <el-upload :show-file-list="false" :before-upload="uploadResults" accept=".csv">
          <el-button type="success">
            <el-icon><Upload /></el-icon> 上传结果
          </el-button>
        </el-upload>
      </div>
    </div>

    <el-row :gutter="16" v-if="plan">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">预估数据点</div>
          <div class="stat-value">{{ plan.estimated_points }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">预估时间</div>
          <div class="stat-value">{{ plan.estimated_time_min }} 分钟</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">已上传结果</div>
          <div class="stat-value">{{ results.length }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">成功 / 失败</div>
          <div class="stat-value">{{ okCount }} / {{ failedCount }}</div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" v-if="plan">
      <el-col :span="10">
        <div class="card">
          <h3 style="margin-bottom: 12px">扫描变量</h3>
          <el-table :data="variablesList" size="small" border>
            <el-table-column prop="name" label="变量" width="120" />
            <el-table-column prop="unit" label="单位" width="70" />
            <el-table-column prop="count" label="数量" width="70" />
            <el-table-column prop="values" label="取值" />
          </el-table>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="card">
          <h3 style="margin-bottom: 12px">方案JSON</h3>
          <pre style="background: #f8fafc; padding: 12px; border-radius: 4px; font-size: 11px; max-height: 300px; overflow: auto">{{ JSON.stringify(plan.plan_data, null, 2) }}</pre>
        </div>
      </el-col>
    </el-row>

    <!-- Results Section -->
    <div class="card" v-if="results.length > 0">
      <h3 style="margin-bottom: 12px">仿真结果</h3>
      <el-table :data="results" stripe border size="small" max-height="400">
        <el-table-column prop="run_index" label="#" width="50" fixed />
        <el-table-column v-for="param in paramKeys" :key="param" :label="param" :prop="`params.${param}`" width="100">
          <template #default="{ row }">{{ row.params[param] }}</template>
        </el-table-column>
        <el-table-column prop="metrics.tavg_nm" label="平均转矩(Nm)" width="110">
          <template #default="{ row }">{{ row.metrics.tavg_nm?.toFixed(4) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.ripple_pct" label="转矩脉动(%)" width="110">
          <template #default="{ row }">{{ row.metrics.ripple_pct?.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.efficiency_pct" label="效率(%)" width="90">
          <template #default="{ row }">{{ row.metrics.efficiency_pct?.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.total_losses_w" label="总损耗(W)" width="100">
          <template #default="{ row }">{{ row.metrics.total_losses_w?.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.copper_loss_w" label="铜耗(W)" width="90" />
        <el-table-column prop="metrics.iron_loss_w" label="铁耗(W)" width="90" />
        <el-table-column prop="metrics.back_emf_v" label="反电动势(V)" width="110" />
        <el-table-column prop="metrics.no_load_speed_rpm" label="空载转速(rpm)" width="120" />
        <el-table-column prop="solve_time_s" label="求解时间(s)" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="row.status === 'OK' ? 'success' : 'danger'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-empty v-else description="暂无结果。请上传 scan_results.csv 查看仿真结果。" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Download, Upload } from '@element-plus/icons-vue'
import { planApi } from '@/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const plan = ref<any>(null)
const results = ref<any[]>([])

const variablesList = computed(() => {
  if (!plan.value?.plan_data?.variables) return []
  return plan.value.plan_data.variables.map((v: any) => ({
    name: v.name,
    unit: v.unit || '',
    count: v.values?.length || 0,
    values: v.values?.join(', ') || ''
  }))
})

const paramKeys = computed(() => {
  if (results.value.length === 0) return []
  return Object.keys(results.value[0].params || {})
})

const okCount = computed(() => results.value.filter(r => r.status === 'OK').length)
const failedCount = computed(() => results.value.filter(r => r.status !== 'OK').length)

async function loadPlan() {
  loading.value = true
  try {
    const id = Number(route.params.id)
    const res = await planApi.get(id)
    plan.value = res.data
    const resultsRes = await planApi.getResults(id)
    results.value = resultsRes.data.items
  } catch (e: any) {
    ElMessage.error('加载方案失败：' + e.message)
  } finally {
    loading.value = false
  }
}

function downloadPlan() {
  const data = JSON.stringify(plan.value.plan_data, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${plan.value.plan_id}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('方案JSON已下载')
}

async function uploadResults(file: File) {
  try {
    const id = Number(route.params.id)
    const res = await planApi.uploadResults(id, file)
    ElMessage.success(`已上传 ${res.data.count} 条结果`)
    await loadPlan()
  } catch (e: any) {
    ElMessage.error('上传失败：' + e.message)
  }
  return false
}

function goBack() {
  if (plan.value?.project_id) {
    router.push(`/projects/${plan.value.project_id}`)
  } else {
    router.push('/projects')
  }
}

function planStatusType(status: string) {
  const map: Record<string, string> = { draft: 'info', confirmed: 'warning', executing: 'primary', completed: 'success', failed: 'danger' }
  return map[status] || 'info'
}

onMounted(loadPlan)
</script>
