<template>
  <div class="page-container" v-loading="loading">
    <div class="page-header">
      <span class="page-title">结果分析仪表盘</span>
      <div class="header-controls">
        <el-select v-model="selectedProject" placeholder="选择项目" style="width: 220px" @change="onProjectChange" clearable>
          <el-option v-for="p in projects" :key="p.id" :label="p.name" :value="p.id" />
        </el-select>
        <el-select v-model="selectedPlan" placeholder="选择方案" style="width: 220px" @change="loadAllCharts" :disabled="!selectedProject" clearable>
          <el-option v-for="p in planList" :key="p.id" :label="`${p.name} (${p.result_count || 0} 结果)`" :value="p.id" />
        </el-select>
      </div>
    </div>

    <!-- Stats Cards -->
    <el-row :gutter="16" class="stats-row" v-if="overview">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">方案总数</div>
          <div class="stat-value">{{ overview.total_plans }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">结果（成功/失败）</div>
          <div class="stat-value">{{ overview.ok_results }}<span class="stat-sub">/{{ overview.total_results }}</span></div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-success">
          <div class="stat-label">最高效率</div>
          <div class="stat-value">{{ overview.best_efficiency_pct }}<span class="stat-sub">%</span></div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card stat-primary">
          <div class="stat-label">最大转矩</div>
          <div class="stat-value">{{ overview.best_torque_nm }}<span class="stat-sub">Nm</span></div>
        </div>
      </el-col>
    </el-row>

    <!-- Chart Controls -->
    <el-row :gutter="16" class="chart-controls" v-if="selectedPlan">
      <el-col :span="12">
        <div class="card">
          <div class="card-header">
            <h3>参数-指标趋势图</h3>
            <div class="chart-selectors">
              <el-select v-model="trendParam" size="small" style="width: 130px" @change="loadTrendChart">
                <el-option v-for="p in availableParams" :key="p" :label="p" :value="p" />
              </el-select>
              <el-select v-model="trendMetric" size="small" style="width: 150px" @change="loadTrendChart">
                <el-option v-for="m in metricOptions" :key="m.key" :label="`${m.label} (${m.unit})`" :value="m.key" />
              </el-select>
            </div>
          </div>
          <div ref="trendChartRef" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="card">
          <div class="card-header">
            <h3>Pareto前沿</h3>
            <div class="chart-selectors">
              <el-select v-model="paretoX" size="small" style="width: 140px" @change="loadParetoChart">
                <el-option v-for="m in metricOptions" :key="m.key" :label="m.label" :value="m.key" />
              </el-select>
              <span style="color: #909399; font-size: 12px">vs</span>
              <el-select v-model="paretoY" size="small" style="width: 140px" @change="loadParetoChart">
                <el-option v-for="m in metricOptions" :key="m.key" :label="m.label" :value="m.key" />
              </el-select>
            </div>
          </div>
          <div ref="paretoChartRef" class="chart-container"></div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="chart-controls" v-if="selectedPlan">
      <el-col :span="12">
        <div class="card">
          <div class="card-header">
            <h3>参数敏感性分析</h3>
            <el-select v-model="sensitivityMetric" size="small" style="width: 180px" @change="loadSensitivityChart">
              <el-option v-for="m in metricOptions" :key="m.key" :label="`${m.label} (${m.unit})`" :value="m.key" />
            </el-select>
          </div>
          <div ref="sensitivityChartRef" class="chart-container"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="card">
          <div class="card-header">
            <h3>结果数据表</h3>
            <el-tag size="small" type="info">{{ filteredResults.length }} 个数据点</el-tag>
          </div>
          <el-table :data="filteredResults" size="small" stripe max-height="320">
            <el-table-column prop="run_index" label="#" width="50" fixed />
            <el-table-column v-for="p in availableParams" :key="p" :label="p" :prop="`params.${p}`" width="90">
              <template #default="{ row }">{{ row.params?.[p] }}</template>
            </el-table-column>
            <el-table-column prop="metrics.tavg_nm" label="平均转矩" width="90">
              <template #default="{ row }">{{ row.metrics?.tavg_nm?.toFixed(3) }}</template>
            </el-table-column>
            <el-table-column prop="metrics.efficiency_pct" label="效率%" width="75">
              <template #default="{ row }">{{ row.metrics?.efficiency_pct?.toFixed(1) }}</template>
            </el-table-column>
            <el-table-column prop="metrics.ripple_pct" label="脉动%" width="75">
              <template #default="{ row }">{{ row.metrics?.ripple_pct?.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="70">
              <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-col>
    </el-row>

    <el-empty v-if="!selectedProject && !loading" description="请选择项目以查看分析仪表盘" :image-size="80" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { projectApi, planApi, analyticsApi } from '@/api'

const loading = ref(false)
const projects = ref<any[]>([])
const selectedProject = ref<number | null>(null)
const selectedPlan = ref<number | null>(null)
const planList = ref<any[]>([])
const overview = ref<any>(null)
const planResults = ref<any[]>([])

// Chart refs
const trendChartRef = ref<HTMLElement>()
const paretoChartRef = ref<HTMLElement>()
const sensitivityChartRef = ref<HTMLElement>()
let trendChart: echarts.ECharts | null = null
let paretoChart: echarts.ECharts | null = null
let sensitivityChart: echarts.ECharts | null = null

// Chart controls
const trendParam = ref('Airgap')
const trendMetric = ref('tavg_nm')
const paretoX = ref('total_losses_w')
const paretoY = ref('efficiency_pct')
const sensitivityMetric = ref('tavg_nm')

const metricOptions = ref<any[]>([])
const availableParams = computed(() => {
  const params = new Set<string>()
  for (const r of planResults.value) {
    if (r.params) {
      for (const k of Object.keys(r.params)) params.add(k)
    }
  }
  return Array.from(params)
})

const filteredResults = computed(() => planResults.value.filter(r => r.status === 'OK'))

async function loadProjects() {
  try {
    const res = await projectApi.list({ limit: 100 })
    projects.value = res.data.items
  } catch (e: any) {
    ElMessage.error('加载项目失败：' + e.message)
  }
}

async function loadMetrics() {
  try {
    const res = await analyticsApi.listMetrics()
    metricOptions.value = res.data.metrics
  } catch (e: any) {
    console.error('Failed to load metrics:', e)
  }
}

async function onProjectChange(projectId: number | null) {
  selectedPlan.value = null
  planList.value = []
  overview.value = null
  planResults.value = []
  if (!projectId) return
  loading.value = true
  try {
    const [overviewRes, plansRes] = await Promise.all([
      analyticsApi.projectOverview(projectId),
      planApi.list({ project_id: projectId, limit: 100 })
    ])
    overview.value = overviewRes.data
    planList.value = plansRes.data.items
  } catch (e: any) {
    ElMessage.error('加载项目概览失败：' + e.message)
  } finally {
    loading.value = false
  }
}

async function loadPlanResults() {
  if (!selectedPlan.value) return
  try {
    const res = await planApi.getResults(selectedPlan.value)
    planResults.value = res.data.items
    // Set default trend param from available params
    if (availableParams.value.length > 0 && !availableParams.value.includes(trendParam.value)) {
      trendParam.value = availableParams.value[0]
    }
  } catch (e: any) {
    ElMessage.error('加载方案结果失败：' + e.message)
  }
}

async function loadAllCharts() {
  if (!selectedPlan.value) return
  loading.value = true
  await loadPlanResults()
  await nextTick()
  initCharts()
  loadTrendChart()
  loadParetoChart()
  loadSensitivityChart()
  loading.value = false
}

function initCharts() {
  if (trendChartRef.value && !trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }
  if (paretoChartRef.value && !paretoChart) {
    paretoChart = echarts.init(paretoChartRef.value)
  }
  if (sensitivityChartRef.value && !sensitivityChart) {
    sensitivityChart = echarts.init(sensitivityChartRef.value)
  }
}

async function loadTrendChart() {
  if (!selectedPlan.value || !trendChart) return
  try {
    const res = await analyticsApi.planTrend(selectedPlan.value, trendParam.value, trendMetric.value)
    const data = res.data
    const metricDef = metricOptions.value.find(m => m.key === trendMetric.value)
    trendChart.setOption({
      tooltip: { trigger: 'axis', formatter: (params: any) => {
        const p = params[0]
        return `${trendParam.value}: ${p.value[0]}<br/>${data.y_label}: ${p.value[1]} ${data.y_unit}`
      }},
      grid: { left: 60, right: 20, top: 30, bottom: 40 },
      xAxis: { type: 'value', name: trendParam.value, nameLocation: 'middle', nameGap: 25 },
      yAxis: { type: 'value', name: data.y_label, nameLocation: 'middle', nameGap: 50 },
      series: [{
        type: 'scatter',
        data: data.points,
        symbolSize: 10,
        itemStyle: { color: '#3b82f6' },
        markLine: {
          silent: true,
          data: [{ type: 'average', name: '平均值' }],
          lineStyle: { color: '#94a3b8', type: 'dashed' }
        }
      }]
    })
  } catch (e: any) {
    console.error('Trend chart error:', e)
  }
}

async function loadParetoChart() {
  if (!selectedPlan.value || !paretoChart) return
  try {
    const res = await analyticsApi.planPareto(selectedPlan.value, paretoX.value, paretoY.value)
    const data = res.data
    const allPts = data.all_points.map((p: any) => [p.x, p.y])
    const paretoPts = data.pareto_points.map((p: any) => [p.x, p.y])
    paretoChart.setOption({
      tooltip: { trigger: 'item', formatter: (p: any) => `${data.x_label}: ${p.value[0]} ${data.x_unit}<br/>${data.y_label}: ${p.value[1]} ${data.y_unit}` },
      legend: { data: ['全部数据点', 'Pareto前沿'], top: 0 },
      grid: { left: 60, right: 20, top: 40, bottom: 40 },
      xAxis: { type: 'value', name: data.x_label, nameLocation: 'middle', nameGap: 25 },
      yAxis: { type: 'value', name: data.y_label, nameLocation: 'middle', nameGap: 50 },
      series: [
        { name: '全部数据点', type: 'scatter', data: allPts, symbolSize: 8, itemStyle: { color: '#cbd5e1' } },
        { name: 'Pareto前沿', type: 'line', data: paretoPts, symbolSize: 12, lineStyle: { color: '#ef4444', width: 2 }, itemStyle: { color: '#ef4444' } }
      ]
    })
  } catch (e: any) {
    console.error('Pareto chart error:', e)
  }
}

async function loadSensitivityChart() {
  if (!selectedPlan.value || !sensitivityChart) return
  try {
    const res = await analyticsApi.planSensitivity(selectedPlan.value, sensitivityMetric.value)
    const data = res.data
    const items = data.items || []
    sensitivityChart.setOption({
      tooltip: { trigger: 'axis', formatter: (params: any) => {
        const p = params[0]
        const item = items[p.dataIndex]
        return `${item.param}<br/>相关系数: ${item.correlation}<br/>方向: ${item.direction}`
      }},
      grid: { left: 100, right: 30, top: 30, bottom: 30 },
      xAxis: { type: 'value', name: '|相关系数|', max: 1, nameLocation: 'middle', nameGap: 25 },
      yAxis: { type: 'category', data: items.map((i: any) => i.param), inverse: true },
      series: [{
        type: 'bar',
        data: items.map((i: any) => ({
          value: i.abs_correlation,
          itemStyle: { color: i.direction === 'positive' ? '#22c55e' : '#ef4444' }
        })),
        barWidth: '50%',
        label: { show: true, position: 'right', formatter: (p: any) => items[p.dataIndex].correlation }
      }]
    })
  } catch (e: any) {
    console.error('Sensitivity chart error:', e)
  }
}

function handleResize() {
  trendChart?.resize()
  paretoChart?.resize()
  sensitivityChart?.resize()
}

onMounted(() => {
  loadProjects()
  loadMetrics()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  paretoChart?.dispose()
  sensitivityChart?.dispose()
})
</script>

<style scoped>
.page-container {
  padding: 20px 24px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
}
.header-controls {
  display: flex;
  gap: 12px;
}
.stats-row {
  margin-bottom: 16px;
}
.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px 20px;
  border: 1px solid #e2e8f0;
}
.stat-label {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 6px;
}
.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
}
.stat-sub {
  font-size: 14px;
  font-weight: 400;
  color: #94a3b8;
  margin-left: 2px;
}
.stat-success .stat-value { color: #16a34a; }
.stat-primary .stat-value { color: #2563eb; }
.chart-controls {
  margin-bottom: 16px;
}
.chart-controls :deep(.el-col) {
  display: flex;
}
.card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e2e8f0;
  width: 100%;
  display: flex;
  flex-direction: column;
  min-height: 400px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-shrink: 0;
}
.card-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}
.chart-selectors {
  display: flex;
  gap: 8px;
  align-items: center;
}
.chart-container {
  width: 100%;
  flex: 1;
  min-height: 320px;
}
.chart-container :deep(canvas) {
  width: 100% !important;
}
</style>
