<template>
  <div class="card">
    <div class="panel-title">
      <span class="title-dot"></span>
      <span>设备概况</span>
    </div>
    <div class="panel-body overview-body">
      <div v-for="item in overviewItems" :key="item.key" class="gauge-item">
        <div class="gauge" :style="getGaugeStyle(item.percent, item.color)">
          <div class="gauge-inner">
            <div class="gauge-value">{{ item.value }}</div>
            <div class="gauge-label">{{ item.label }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { colors } from '../utils'
import { DashboardApi } from '@/api/dashboard'

type OverviewItemKey = 'device' | 'running' | 'idle' | 'alarm' | 'utilization' | 'faultRate'

interface OverviewItem {
  key: OverviewItemKey
  label: string
  value: string
  percent: number
  color: string
}

const route = useRoute()
const orgId = route.query.orgId

const overviewItems = ref<OverviewItem[]>([
  { key: 'device', label: '设备数量', value: '0', percent: 0, color: colors.cyan },
  { key: 'running', label: '运行数量', value: '0', percent: 0, color: colors.blue },
  { key: 'idle', label: '待机数量', value: '0', percent: 0, color: colors.warn },
  { key: 'alarm', label: '报警数量', value: '0', percent: 0, color: colors.danger },
  { key: 'utilization', label: '稼动率', value: '0%', percent: 0, color: colors.green },
  { key: 'faultRate', label: '故障率', value: '0%', percent: 0, color: colors.purple }
])

const getGaugeStyle = (percent: number, color: string) => {
  const p = Math.max(0, Math.min(100, percent))
  return {
    background: `conic-gradient(${color} ${p * 3.6}deg, rgba(148,163,184,0.18) 0deg)`
  }
}

const formatNumber = (value: number | string | undefined | null) => {
  const n = Number(value ?? 0)
  if (!Number.isFinite(n)) return '0'
  return n.toLocaleString('zh-CN')
}

const calcPercent = (part: number, total: number) => {
  if (!total || total <= 0 || !Number.isFinite(part)) return 0
  const raw = (part / total) * 100
  return Math.max(0, Math.min(100, Math.round(raw)))
}

const loadOverview = async () => {
  try {
    const res: any = await DashboardApi.getDeviceOperationalStatus({ orgId })
    const data = (res && typeof res === 'object' ? (res.data ?? res) : {}) as any

    const totalDevices = Number(data.totalDevices ?? 0)
    const runningCount = Number(data.runningCount ?? 0)
    const standbyCount = Number(data.standbyCount ?? 0)
    const faultCount = Number(data.faultCount ?? 0)
    const warningCount = Number(data.warningCount ?? 0)

    const utilizationRateRaw = String(data.utilizationRate ?? '0')
    const faultRateRaw = String(data.faultRate ?? '0')

    const utilizationPercent = Number.parseFloat(utilizationRateRaw.replace('%', '')) || 0
    const faultPercent = Number.parseFloat(faultRateRaw.replace('%', '')) || 0

    const alarmCount = faultCount + warningCount

    overviewItems.value = overviewItems.value.map((item) => {
      if (item.key === 'device') {
        return {
          ...item,
          value: formatNumber(totalDevices),
          percent: calcPercent(totalDevices, totalDevices || 1)
        }
      }
      if (item.key === 'running') {
        return {
          ...item,
          value: formatNumber(runningCount),
          percent: calcPercent(runningCount, totalDevices)
        }
      }
      if (item.key === 'idle') {
        return {
          ...item,
          value: formatNumber(standbyCount),
          percent: calcPercent(standbyCount, totalDevices)
        }
      }
      if (item.key === 'alarm') {
        return {
          ...item,
          value: formatNumber(alarmCount),
          percent: calcPercent(alarmCount, totalDevices)
        }
      }
      if (item.key === 'utilization') {
        const p = Math.max(0, Math.min(100, Math.round(utilizationPercent)))
        return {
          ...item,
          value: utilizationRateRaw.includes('%') ? utilizationRateRaw : `${utilizationPercent.toFixed(2)}%`,
          percent: p
        }
      }
      if (item.key === 'faultRate') {
        const p = Math.max(0, Math.min(100, Math.round(faultPercent)))
        return {
          ...item,
          value: faultRateRaw.includes('%') ? faultRateRaw : `${faultPercent.toFixed(2)}%`,
          percent: p
        }
      }
      return item
    })
  } catch (e) {
  }
}

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

<style scoped>
.card {
  position: relative;
  display: flex;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background: linear-gradient(135deg, rgb(15 23 42 / 96%), rgb(15 23 42 / 88%));
  border: 1px solid rgb(30 64 175 / 85%);
  border-radius: 8px;
  box-shadow:
    0 18px 45px rgb(15 23 42 / 95%),
    0 0 0 1px rgb(15 23 42 / 100%),
    inset 0 0 0 1px rgb(56 189 248 / 5%);
  flex-direction: column;
}

.card::before,
.card::after {
  position: absolute;
  width: 12px;
  height: 12px;
  pointer-events: none;
  border: 1px solid rgb(56 189 248 / 75%);
  border-radius: 2px;
  content: "";
  opacity: 0.6;
}

.card::before {
  top: -1px;
  left: -1px;
  border-right: none;
  border-bottom: none;
}

.card::after {
  right: -1px;
  bottom: -1px;
  border-top: none;
  border-left: none;
}

.panel-title {
  display: flex;
  padding: 10px 12px;
  font-size: 16px;
  font-weight: 900;
  color: #e5f0ff;
  border-bottom: 1px solid rgb(41 54 95 / 90%);
  align-items: center;
  gap: 10px;
}

.title-dot {
  width: 10px;
  height: 10px;
  border: 1px solid rgb(56 189 248 / 95%);
  border-radius: 50%;
  box-shadow: 0 0 12px rgb(56 189 248 / 45%);
}

.panel-body {
  flex: 1;
  min-height: 0;
  padding: 10px 12px;
}

.overview-body {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.gauge-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.gauge {
  width: 110px;
  height: 110px;
  padding: 8px;
  border-radius: 50%;
  box-sizing: border-box;
}

.gauge-inner {
  display: flex;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgb(2 6 23 / 92%);
  border: 1px solid rgb(148 163 184 / 25%);
  border-radius: 50%;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2px;
}

.gauge-value {
  font-size: 18px;
  font-weight: 900;
  color: #e5f0ff;
}

.gauge-label {
  font-size: 11px;
  color: rgb(148 163 184 / 95%);
}

@media (width <= 1366px) {
  .gauge {
    width: 96px;
    height: 96px;
  }
}
</style>
