<template>
  <div class="workbench-panel">
    <el-tabs v-model="activeNav" class="nav-tabs" @tab-change="onNavChange">
      <el-tab-pane label="地图" name="map" />
      <el-tab-pane label="进程" name="process" />
      <el-tab-pane label="车辆" name="vehicle" />
      <el-tab-pane label="场景" name="scene" />
      <el-tab-pane label="脚本" name="script" />
    </el-tabs>

    <div class="toolbar-hint muted">
      {{ navHint }}
    </div>

    <el-input
      v-model="search"
      size="small"
      clearable
      placeholder="搜索（多词空格分隔）"
      class="search-input"
    />

    <el-table
      :data="filteredRows"
      size="small"
      stripe
      highlight-current-row
      :row-class-name="rowClassName"
      max-height="280"
      class="list-table"
      @row-click="onRowClick"
    >
      <el-table-column
        v-for="col in list?.columns ?? []"
        :key="col"
        :prop="columnProp(col)"
        :label="col"
        min-width="72"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ cellValue(row, col) }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { listWorkbench } from '@/api/workbench'
import type { WorkbenchList, WorkbenchListRow, WorkbenchNav, SelectedObjectRef } from '@/types/workbench'

const props = defineProps<{
  refreshKey?: number
}>()

const emit = defineEmits<{
  select: [ref: SelectedObjectRef]
}>()

const activeNav = ref<WorkbenchNav>('vehicle')
const list = ref<WorkbenchList | null>(null)
const search = ref('')
const selectedId = ref<string | null>(null)

const navHints: Record<WorkbenchNav, string> = {
  map: '地图/装饰对象列表（对齐 SimpleLite 工作台「地图」）',
  process: '自定义进程 Mission 列表',
  vehicle: '场景车辆列表（ID / 地址 / 名称 / 概况）',
  scene: '站点、路径、装饰物',
  script: '每辆车挂载的 CarProgram'
}

const navHint = computed(() => navHints[activeNav.value])

const filteredRows = computed(() => {
  const rows = list.value?.rows ?? []
  const q = search.value.trim().toLowerCase()
  if (!q) return rows
  const tokens = q.split(/\s+/).filter(Boolean)
  return rows.filter((row) =>
    tokens.every((t) => rowMatches(row, t))
  )
})

function rowMatches(row: WorkbenchListRow, token: string): boolean {
  const parts = [
    row.id,
    row.name,
    row.type,
    row.status,
    row.overview ?? '',
    ...Object.values(row.cells ?? {})
  ]
  return parts.some((p) => p.toLowerCase().includes(token))
}

function columnProp(col: string): string {
  const map: Record<string, keyof WorkbenchListRow> = {
    ID: 'id',
    名称: 'name',
    类型: 'type',
    图层: 'status',
    状态: 'status',
    信息: 'status',
    概况: 'overview',
    地址: 'status',
    车辆: 'name',
    脚本名: 'type'
  }
  return (map[col] ?? 'name') as string
}

function cellValue(row: WorkbenchListRow, col: string): string {
  if (row.cells?.[col]) return row.cells[col]
  const prop = columnProp(col)
  const v = row[prop as keyof WorkbenchListRow]
  if (prop === 'overview' && row.overview) return row.overview
  return v != null ? String(v) : '—'
}

function rowClassName({ row }: { row: WorkbenchListRow }) {
  return row.id === selectedId.value ? 'is-selected-row' : ''
}

function onRowClick(row: WorkbenchListRow) {
  selectedId.value = row.id
  const kind = activeNav.value === 'process' ? 'process'
    : activeNav.value === 'script' ? 'script'
      : activeNav.value
  emit('select', { kind, id: row.id, name: row.name })
}

async function loadList() {
  list.value = await listWorkbench(activeNav.value)
}

function onNavChange() {
  selectedId.value = null
  loadList()
}

watch(() => props.refreshKey, loadList)
watch(activeNav, loadList)

onMounted(loadList)
</script>

<style scoped>
.workbench-panel {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-height: 0;
}
.nav-tabs :deep(.el-tabs__header) { margin-bottom: 0; }
.toolbar-hint { font-size: 11px; line-height: 1.4; }
.search-input { flex: none; }
.list-table { flex: 1; min-height: 0; }
.workbench-panel,
.workbench-panel :deep(.el-tabs__item),
.workbench-panel :deep(.el-table .cell),
.workbench-panel :deep(.el-input__inner) {
  color: var(--mg-text-light);
}
.toolbar-hint { color: var(--mg-text-muted); }
.muted { color: var(--mg-text-muted); }
:deep(.el-table th.el-table__cell) {
  color: var(--mg-text-muted) !important;
}
:deep(.is-selected-row) td {
  background: rgba(var(--mg-primary-hover-rgb), 0.28) !important;
  color: var(--mg-text-light) !important;
}
</style>
