<template>
  <div class="page-container">
    <div class="page-header">
      <span class="page-title">仿真项目</span>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon> 新建项目
      </el-button>
    </div>

    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">项目总数</div>
          <div class="stat-value">{{ total }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">SSSR拓扑</div>
          <div class="stat-value">{{ sssrCount }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">进行中</div>
          <div class="stat-value">{{ activeCount }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">已完成</div>
          <div class="stat-value">{{ completedCount }}</div>
        </div>
      </el-col>
    </el-row>

    <div class="card">
      <el-table :data="projects" v-loading="loading" stripe @row-click="goToProject">
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="name" label="项目名称" min-width="200">
          <template #default="{ row }">
            <span style="color: #3b82f6; cursor: pointer; font-weight: 500">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="topology" label="拓扑结构" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="row.topology === 'SSSR' ? 'primary' : 'warning'">{{ row.topology }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag size="small" :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="plan_count" label="方案数" width="80" />
        <el-table-column prop="description" label="项目描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="updated_at" label="更新时间" width="170">
          <template #default="{ row }">{{ formatDate(row.updated_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button size="small" text type="danger" @click.stop="deleteProject(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Create Project Dialog -->
    <el-dialog v-model="showCreateDialog" title="新建项目" width="640px">
      <el-form :model="newProject" label-width="130px">
        <el-form-item label="项目名称">
          <el-input v-model="newProject.name" placeholder="例如：MARS气隙优化" />
        </el-form-item>
        <el-form-item label="拓扑结构">
          <el-select v-model="newProject.topology" style="width: 100%">
            <el-option label="SSSR（单定子单转子）" value="SSSR" />
            <el-option label="DRSS（双转子单定子）" value="DRSS" />
            <el-option label="SDSR（单定子双转子）" value="SDSR" />
          </el-select>
        </el-form-item>
        <el-form-item label="模型路径">
          <el-input v-model="newProject.model_path" placeholder="models/xxx.mot" />
        </el-form-item>
        <el-form-item label="项目描述">
          <el-input v-model="newProject.description" type="textarea" :rows="2" />
        </el-form-item>

        <el-divider content-position="left">边界条件</el-divider>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="外径">
              <el-input-number v-model="bc.outer_diameter_mm" :min="10" :max="500" :step="1" :precision="1" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">mm</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内径">
              <el-input-number v-model="bc.inner_diameter_mm" :min="0" :max="400" :step="1" :precision="1" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">mm</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="转速">
              <el-input-number v-model="bc.speed_rpm" :min="100" :max="50000" :step="500" :precision="0" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">rpm</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效值电流">
              <el-input-number v-model="bc.current_a" :min="0.5" :max="200" :step="1" :precision="1" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">A</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="磁钢温度">
              <el-input-number v-model="bc.magnet_temp_c" :min="-40" :max="200" :step="10" :precision="0" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">°C</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标转矩">
              <el-input-number v-model="bc.target_torque_nm" :min="0" :max="1000" :step="0.1" :precision="2" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">Nm</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="目标效率">
              <el-input-number v-model="bc.target_efficiency_pct" :min="0" :max="100" :step="1" :precision="1" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大损耗">
              <el-input-number v-model="bc.max_losses_w" :min="0" :max="10000" :step="10" :precision="0" controls-position="right" style="width: 100%" />
              <span class="unit-suffix">W</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createProject" :loading="creating">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { projectApi } from '@/api'

const router = useRouter()
const loading = ref(false)
const creating = ref(false)
const projects = ref<any[]>([])
const total = ref(0)
const showCreateDialog = ref(false)
const newProject = ref({ name: '', topology: 'SSSR', model_path: '', description: '' })
const bc = ref<Record<string, number | null>>({
  outer_diameter_mm: null,
  inner_diameter_mm: null,
  speed_rpm: null,
  current_a: null,
  magnet_temp_c: null,
  target_torque_nm: null,
  target_efficiency_pct: null,
  max_losses_w: null,
})

const sssrCount = computed(() => projects.value.filter(p => p.topology === 'SSSR').length)
const activeCount = computed(() => projects.value.filter(p => p.status === 'active').length)
const completedCount = computed(() => projects.value.filter(p => p.status === 'completed').length)

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

async function createProject() {
  if (!newProject.value.name.trim()) {
    ElMessage.warning('请输入项目名称')
    return
  }
  creating.value = true
  try {
    // Build boundary_conditions from non-null bc values + topology
    const boundaryConditions: Record<string, any> = { topology: newProject.value.topology }
    for (const [key, val] of Object.entries(bc.value)) {
      if (val !== null && val !== undefined) {
        boundaryConditions[key] = val
      }
    }
    const payload = { ...newProject.value, boundary_conditions: boundaryConditions }
    await projectApi.create(payload)
    ElMessage.success('项目创建成功')
    showCreateDialog.value = false
    newProject.value = { name: '', topology: 'SSSR', model_path: '', description: '' }
    bc.value = {
      outer_diameter_mm: null, inner_diameter_mm: null, speed_rpm: null,
      current_a: null, magnet_temp_c: null, target_torque_nm: null,
      target_efficiency_pct: null, max_losses_w: null,
    }
    await loadProjects()
  } catch (e: any) {
    ElMessage.error('创建项目失败：' + e.message)
  } finally {
    creating.value = false
  }
}

async function deleteProject(id: number) {
  try {
    await ElMessageBox.confirm('确定删除此项目及其所有方案和结果？', '确认删除', { type: 'warning' })
    await projectApi.delete(id)
    ElMessage.success('项目已删除')
    await loadProjects()
  } catch (e: any) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  }
}

function goToProject(row: any) {
  router.push(`/projects/${row.id}`)
}

function statusType(status: string) {
  const map: Record<string, string> = { draft: 'info', active: 'primary', completed: 'success', archived: 'warning' }
  return map[status] || 'info'
}

function formatDate(d: string) {
  return new Date(d).toLocaleString()
}

onMounted(loadProjects)
</script>

<style scoped>
.stats-row {
  margin-bottom: 16px;
}
.unit-suffix {
  margin-left: 8px;
  color: #909399;
  font-size: 13px;
}
</style>
