<script setup>
import { Plus, Refresh, Delete, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import {
  getExperiments,
  createExperiment,
  deleteExperiment,
  getMonitorModels,
} from '@/api/realtimeMonitor'

const router = useRouter()

// ── 试验列表 ───────────────────────────────────────────────────────────────────
const experiments = ref([])
const loading = ref(false)

const loadExperiments = async () => {
  loading.value = true
  try {
    experiments.value = await getExperiments()
  } finally {
    loading.value = false
  }
}

// ── 创建对话框 ─────────────────────────────────────────────────────────────────
const dialogVisible = ref(false)
const submitting = ref(false)
const models = ref([])

const defaultMpcParams = () => ({
  P: 20,
  M: 5,
  Q: 10.0,
  R: 0.1,
  alpha: 0.8,
  u_min: 0.0,
  u_max: 10.0,
  du_min: -2.0,
  du_max: 2.0,
  y_min: -50.0,
  y_max: 200.0,
  correction_gain: 0.5,
})

const form = reactive({
  name: '',
  model_id: '',
  input_csv_path: '',
  output_csv_path: '',
  target_temp: 35.0,
  sampling_interval: 1.0,
  mpc_params: defaultMpcParams(),
})

const showAdvanced = ref(false)

const openDialog = async () => {
  Object.assign(form, {
    name: '',
    model_id: '',
    input_csv_path: '',
    output_csv_path: '',
    target_temp: 35.0,
    sampling_interval: 1.0,
    mpc_params: defaultMpcParams(),
  })
  showAdvanced.value = false
  dialogVisible.value = true
  if (!models.value.length) {
    models.value = await getMonitorModels()
  }
}

const handleCreate = async () => {
  if (!form.name.trim()) { ElMessage.warning('请输入试验名称'); return }
  if (!form.model_id) { ElMessage.warning('请选择预测模型'); return }
  if (!form.input_csv_path.trim()) { ElMessage.warning('请输入输入CSV文件路径'); return }
  if (!form.output_csv_path.trim()) { ElMessage.warning('请输入输出CSV文件路径'); return }

  submitting.value = true
  try {
    await createExperiment({
      name: form.name.trim(),
      model_id: form.model_id,
      input_csv_path: form.input_csv_path.trim(),
      output_csv_path: form.output_csv_path.trim(),
      target_temp: form.target_temp,
      sampling_interval: form.sampling_interval,
      mpc_params: { ...form.mpc_params },
    })
    ElMessage.success('试验创建成功')
    dialogVisible.value = false
    await loadExperiments()
  } finally {
    submitting.value = false
  }
}

// ── 删除试验 ───────────────────────────────────────────────────────────────────
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除试验"${row.name}"吗？相关数据将一并删除。`,
      '删除确认',
      { type: 'warning' },
    )
    await deleteExperiment(row.id)
    ElMessage.success('试验已删除')
    await loadExperiments()
  } catch {
    // 用户取消
  }
}

// ── 进入详情 ───────────────────────────────────────────────────────────────────
const handleView = (row) => {
  router.push({ name: 'realtime-monitor-detail', params: { id: row.id } })
}

// ── 状态标签 ───────────────────────────────────────────────────────────────────
const statusType = (s) => ({ idle: 'info', running: 'success', stopped: '' }[s] ?? 'info')
const statusLabel = (s) => ({ idle: '未开始', running: '运行中', stopped: '已停止' }[s] ?? s)

onMounted(loadExperiments)
</script>

<template>
  <div class="monitor-page">
    <!-- 页头 -->
    <el-card shadow="hover" class="page-card">
      <template #header>
        <div class="card-header-row">
          <span class="card-title">试验管理</span>
          <div class="header-actions">
            <el-button :icon="Refresh" size="small" plain :loading="loading" @click="loadExperiments">
              刷新
            </el-button>
            <el-button type="primary" :icon="Plus" size="small" @click="openDialog">
              创建试验
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="experiments" v-loading="loading" stripe>
        <el-table-column prop="name" label="试验名称" min-width="160" />
        <el-table-column prop="model_name" label="预测模型" min-width="140" />
        <el-table-column prop="input_csv_path" label="输入CSV" min-width="180" show-overflow-tooltip />
        <el-table-column prop="target_temp" label="目标温度(°C)" width="120" align="right">
          <template #default="{ row }">{{ row.target_temp?.toFixed(1) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_steps" label="已采集步数" width="110" align="right" />
        <el-table-column prop="created_at" label="创建时间" width="160" />
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" :icon="View" link @click="handleView(row)">
              进入
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              link
              :disabled="row.status === 'running'"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建试验对话框 -->
    <el-dialog v-model="dialogVisible" title="创建试验" width="640px" :close-on-click-modal="false">
      <el-form label-width="140px" @submit.prevent>
        <el-form-item label="试验名称" required>
          <el-input v-model="form.name" placeholder="请输入试验名称" />
        </el-form-item>
        <el-form-item label="预测模型" required>
          <el-select v-model="form.model_id" placeholder="选择模型" style="width:100%">
            <el-option v-for="m in models" :key="m.id" :label="m.model_name" :value="m.id">
              <span>{{ m.model_name }}</span>
              <span style="float:right;color:#86909c;font-size:12px">seq={{ m.seq_len }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="输入CSV路径" required>
          <el-input
            v-model="form.input_csv_path"
            placeholder="传感器数据源 CSV 文件的绝对路径"
          />
          <div class="field-hint">每步控制将从该文件末尾读取最新传感器数据</div>
        </el-form-item>
        <el-form-item label="输出CSV路径" required>
          <el-input
            v-model="form.output_csv_path"
            placeholder="生成曲线写入的 CSV 文件绝对路径"
          />
          <div class="field-hint">MPC 每步控制结果（温度、电流）将追加写入该文件</div>
        </el-form-item>
        <el-form-item label="目标温度(°C)" required>
          <el-input-number v-model="form.target_temp" :step="0.5" :precision="1" style="width:160px" />
        </el-form-item>
        <el-form-item label="采样周期(s)" required>
          <el-input-number
            v-model="form.sampling_interval"
            :min="0.1"
            :max="3600"
            :step="0.5"
            :precision="1"
            style="width:160px"
          />
          <span style="margin-left:8px;color:#94a3b8;font-size:12px">需与传感器采集频率一致</span>
        </el-form-item>

        <!-- MPC 参数（高级） -->
        <el-divider content-position="left">
          <el-button link type="primary" size="small" @click="showAdvanced = !showAdvanced">
            {{ showAdvanced ? '收起 MPC 参数' : '展开 MPC 参数' }}
          </el-button>
        </el-divider>

        <template v-if="showAdvanced">
          <div class="params-grid">
            <el-form-item label="预测时域 P">
              <el-input-number v-model="form.mpc_params.P" :min="5" :max="100" :step="5" />
            </el-form-item>
            <el-form-item label="控制时域 M">
              <el-input-number v-model="form.mpc_params.M" :min="1" :max="20" />
            </el-form-item>
            <el-form-item label="跟踪权重 Q">
              <el-input-number v-model="form.mpc_params.Q" :min="0.1" :step="1" :precision="1" />
            </el-form-item>
            <el-form-item label="增量权重 R">
              <el-input-number v-model="form.mpc_params.R" :min="0.01" :step="0.05" :precision="3" />
            </el-form-item>
            <el-form-item label="柔化系数 α">
              <el-input-number v-model="form.mpc_params.alpha" :min="0.1" :max="0.99" :step="0.05" :precision="2" />
            </el-form-item>
            <el-form-item label="反馈增益">
              <el-input-number v-model="form.mpc_params.correction_gain" :min="0" :max="1" :step="0.1" :precision="2" />
            </el-form-item>
            <el-form-item label="电流下限(A)">
              <el-input-number v-model="form.mpc_params.u_min" :min="0" :precision="1" />
            </el-form-item>
            <el-form-item label="电流上限(A)">
              <el-input-number v-model="form.mpc_params.u_max" :min="0" :precision="1" />
            </el-form-item>
            <el-form-item label="Δu 下限">
              <el-input-number v-model="form.mpc_params.du_min" :step="0.5" :precision="1" />
            </el-form-item>
            <el-form-item label="Δu 上限">
              <el-input-number v-model="form.mpc_params.du_max" :step="0.5" :precision="1" />
            </el-form-item>
          </div>
        </template>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.monitor-page {
  padding: 20px;
}

.page-card {
  border-radius: 8px;
}

.card-header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.field-hint {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 4px;
  line-height: 1.4;
}

.params-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 16px;
}
</style>

