<template>
  <div class="vehicle-hub-page">
    <div class="hub-toolbar">
      <div class="stats-row">
        <div class="stat">
          <span class="num">{{ totalCount }}</span>
          <span class="label">总数</span>
        </div>
        <div class="stat online">
          <span class="num">{{ onlineCount }}</span>
          <span class="label">在线</span>
        </div>
        <div class="stat warn">
          <span class="num">{{ maintenanceCount }}</span>
          <span class="label">维护中</span>
        </div>
        <div class="stat danger">
          <span class="num">{{ alarmCount }}</span>
          <span class="label">报警</span>
        </div>
        <div class="stat muted">
          <span class="num">{{ unreachableCount }}</span>
          <span class="label">不可达</span>
        </div>
      </div>

      <div class="filters-row">
        <el-input
          v-model="search"
          size="small"
          clearable
          placeholder="搜索 ID / 名称 / IP"
          class="search-input"
          :prefix-icon="Search"
        />
        <el-select v-model="filterState" size="small" clearable placeholder="状态" class="filter-select">
          <el-option v-for="opt in stateOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
        <el-select v-model="filterGroup" size="small" clearable placeholder="群组" class="filter-select">
          <el-option v-for="g in groupOptions" :key="g" :label="g" :value="g" />
        </el-select>
        <el-dropdown :disabled="!canWrite || !selectedIds.length" @command="onBatchCommand">
          <el-button size="small" :disabled="!canWrite || !selectedIds.length">
            批量维护
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="online">批量上线</el-dropdown-item>
              <el-dropdown-item command="offline">批量下线</el-dropdown-item>
              <el-dropdown-item command="repair">批量现场检修</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button size="small" :icon="Refresh" :loading="loading || healthLoading" @click="refreshAll">
          刷新
        </el-button>
      </div>
    </div>

    <div v-loading="loading && !cardModels.length" class="card-grid">
      <VehicleHealthCard
        v-for="v in filteredCards"
        :key="v.id"
        :vehicle="v"
        :selected="selectedId === v.id"
        :can-write="canWrite"
        @select="selectedId = $event"
        @maintenance-changed="refreshAll"
      />
      <el-empty v-if="!filteredCards.length && !loading" description="无匹配车辆" />
    </div>

    <p class="footnote">故障率 = 报警占用时长 ÷ 自上线以来运行时长（SimpleLite 进程内累计）</p>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import VehicleHealthCard from '@/components/fleet/VehicleHealthCard.vue'
import { useVehicleHub } from '@/composables/useVehicleHub'
import { setVehicleMaintenance, type VehicleMaintenanceMode } from '@/api/vehicleOps'
import type { CarState } from '@/types/car'
import { useAuthStore } from '@/stores/auth'

const auth = useAuthStore()
const canWrite = computed(() => auth.scope === 'Platform' || (auth.effectivePermissions?.allowedOps ?? []).includes('*'))

const {
  cardModels,
  loading,
  healthLoading,
  selectedId,
  totalCount,
  onlineCount,
  maintenanceCount,
  alarmCount,
  unreachableCount,
  refreshAll
} = useVehicleHub()

const search = ref('')
const filterState = ref<CarState | ''>('')
const filterGroup = ref('')

const stateOptions: { value: CarState; label: string }[] = [
  { value: 'idle', label: '空闲' },
  { value: 'running', label: '运行' },
  { value: 'charging', label: '充电' },
  { value: 'paused', label: '暂停' },
  { value: 'fault', label: '故障' },
  { value: 'offline', label: '离线' }
]

const groupOptions = computed(() => {
  const set = new Set<string>()
  for (const c of cardModels.value) {
    if (c.group) set.add(c.group)
  }
  return [...set]
})

const filteredCards = computed(() => {
  const q = search.value.trim().toLowerCase()
  const tokens = q ? q.split(/\s+/).filter(Boolean) : []
  return cardModels.value.filter((c) => {
    if (filterState.value && c.state !== filterState.value) return false
    if (filterGroup.value && c.group !== filterGroup.value) return false
    if (!tokens.length) return true
    const hay = [c.id, c.name, c.ip, c.group, c.lstatus].filter(Boolean).join(' ').toLowerCase()
    return tokens.every((t) => hay.includes(t))
  })
})

const selectedIds = computed(() => (selectedId.value ? [selectedId.value] : []))

async function onBatchCommand(cmd: string) {
  const mode = cmd as VehicleMaintenanceMode
  const targets = filteredCards.value.filter((c) => selectedId.value ? c.id === selectedId.value : true)
  if (!targets.length) return
  try {
    await ElMessageBox.confirm(`对 ${targets.length} 辆车执行「${cmd}」？`, '批量维护', { type: 'warning' })
    for (const v of targets) {
      const rawId = v.rawId ?? parseInt(v.id.replace(/\D/g, ''), 10)
      if (Number.isFinite(rawId)) await setVehicleMaintenance(rawId, mode)
    }
    ElMessage.success('批量操作已提交')
    await refreshAll()
  } catch {
    /* cancelled */
  }
}
</script>

<style scoped>
.vehicle-hub-page {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: hidden;
}

.hub-toolbar {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

.stats-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 64px;
}

.stat .num {
  font-size: 22px;
  font-weight: 700;
  line-height: 1.2;
}

.stat .label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.stat.online .num { color: var(--el-color-success); }
.stat.warn .num { color: var(--el-color-warning); }
.stat.danger .num { color: var(--el-color-danger); }
.stat.muted .num { color: var(--el-text-color-secondary); }

.filters-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.search-input {
  width: 220px;
}

.filter-select {
  width: 120px;
}

.card-grid {
  flex: 1;
  overflow: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 12px;
  align-content: start;
  padding-bottom: 8px;
}

.footnote {
  flex-shrink: 0;
  margin: 0;
  font-size: 11px;
  color: var(--el-text-color-placeholder);
}
</style>
