<script setup>
import { computed, onMounted, ref } from 'vue'
import { DataBoard, Histogram, Monitor, Setting } from '@element-plus/icons-vue'

const assets = ref([])
const metrics = ref([])
const records = ref([])
const loading = ref(false)

const fetchJson = async (url) => {
  const res = await fetch(url)
  if (!res.ok) throw new Error(url)
  return res.json()
}

const loadDashboard = async () => {
  loading.value = true
  try {
    const [assetRes, metricRes] = await Promise.all([fetchJson('/api/assets'), fetchJson('/api/metrics')])
    assets.value = assetRes.status === 'success' ? assetRes.data || [] : []
    metrics.value = metricRes.status === 'success' ? metricRes.data || [] : []

    const recordGroups = await Promise.all(
      assets.value.slice(0, 60).map(async (asset) => {
        try {
          const res = await fetchJson(`/api/records?asset_id=${asset.asset_id}`)
          return res.status === 'success' ? res.data || [] : []
        } catch (error) {
          return []
        }
      }),
    )
    records.value = recordGroups.flat()
  } finally {
    loading.value = false
  }
}

const wholeMachines = computed(() => assets.value.filter((item) => item.asset_category === '整机').length)
const components = computed(() => assets.value.filter((item) => item.asset_category === '部件').length)
const recentRecords = computed(() => records.value.slice(0, 6))

onMounted(() => {
  loadDashboard()
})
</script>

<template>
  <div class="overview-page" v-loading="loading">
    <div class="overview-grid">
      <div class="overview-card">
        <el-icon><Monitor /></el-icon>
        <span>整机设备</span>
        <strong>{{ wholeMachines }}</strong>
      </div>
      <div class="overview-card">
        <el-icon><Setting /></el-icon>
        <span>功能部件</span>
        <strong>{{ components }}</strong>
      </div>
      <div class="overview-card">
        <el-icon><Histogram /></el-icon>
        <span>精度指标</span>
        <strong>{{ metrics.length }}</strong>
      </div>
      <div class="overview-card">
        <el-icon><DataBoard /></el-icon>
        <span>测试记录</span>
        <strong>{{ records.length }}</strong>
      </div>
    </div>

    <el-row :gutter="18">
      <el-col :span="14">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-header">
              <span>近期测试记录</span>
              <el-tag type="info">{{ records.length }} 条</el-tag>
            </div>
          </template>
          <el-table :data="recentRecords" stripe>
            <el-table-column prop="metric_name" label="测定指标" min-width="220" />
            <el-table-column prop="value_type" label="数据属性" width="110" />
            <el-table-column prop="created_at" label="录入时间" width="180" />
          </el-table>
          <el-empty v-if="!recentRecords.length" description="暂无测试记录，请先在设备台账中建设备并配置指标，再到数据录入页面填写测定数据" />
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-header">
              <span>设备概览</span>
              <el-tag type="primary">{{ assets.length }} 台/件</el-tag>
            </div>
          </template>
          <div class="asset-list">
            <div v-for="asset in assets.slice(0, 8)" :key="asset.asset_id" class="asset-row">
              <div>
                <strong>{{ asset.asset_code }}</strong>
                <span>{{ asset.asset_name }}</span>
              </div>
              <el-tag :type="asset.asset_category === '整机' ? 'primary' : 'success'" size="small">
                {{ asset.asset_category }}
              </el-tag>
            </div>
            <el-empty v-if="!assets.length" description="暂无设备资产，请先进入设备台账新增整机或部件" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.overview-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 16px;
  margin-bottom: 18px;
}

.overview-card {
  min-height: 128px;
  padding: 22px;
  border-radius: 24px;
  background: linear-gradient(145deg, rgba(250, 252, 255, 0.94), rgba(235, 244, 252, 0.86));
  border: 1px solid rgba(255, 255, 255, 0.9);
  box-shadow: 0 14px 28px rgba(111, 133, 166, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.86);
}

.overview-card .el-icon {
  width: 38px;
  height: 38px;
  margin-bottom: 16px;
  border-radius: 14px;
  color: #5f88bc;
  background: rgba(255, 255, 255, 0.56);
}

.overview-card span {
  display: block;
  color: #66768d;
  font-size: 13px;
}

.overview-card strong {
  display: block;
  margin-top: 6px;
  color: #203553;
  font-size: 30px;
}

.panel-card {
  border-radius: 24px;
}

.asset-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.asset-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 14px;
  border-radius: 16px;
  background: rgba(245, 249, 253, 0.72);
}

.asset-row strong,
.asset-row span {
  display: block;
}

.asset-row span {
  margin-top: 3px;
  color: #66768d;
  font-size: 13px;
}
</style>
