<template>
  <BaseCard title="实时交易统计">
    <template #headerExtra>
      <DateIndicatorTabs
        v-model="currentDimension"
        :items="timeDimensions"
      />
    </template>

    <div class="stats-container">
      <div
        v-for="item in statItems"
        :key="item.key"
        class="stat-item"
      >
        <div class="stat-visual">
          <div class="stat-value">
            <div class="stat-number">{{ formatNumber(statsData[item.key]) }}</div>
            <div class="stat-unit">({{ item.unit }})</div>
          </div>
          <img
            class="stat-platform"
            src="/images/数据底板.png"
            alt=""
          />
        </div>
        <div class="stat-label">{{ item.label }}</div>
      </div>
    </div>
  </BaseCard>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import BaseCard from './BaseCard.vue'
import DateIndicatorTabs from './DateIndicatorTabs.vue'
import { dataManager } from '../utils/dataManager.js'

const timeDimensions = [
  { key: 'day', label: '日' },
  { key: 'week', label: '周' },
  { key: 'month', label: '月' }
]

const statItems = [
  { key: 'mnjyzl', unit: '头', label: '牦牛交易总量' },
  { key: 'jdjyzl', unit: '笔', label: '订单交易总量' },
  { key: 'xsshsl', unit: '户', label: '销售商户数量' },
  { key: 'cgshsl', unit: '户', label: '采购商户数量' }
]

const currentDimension = ref('day')

const metricKeys = ['mnjyzl', 'jdjyzl', 'xsshsl', 'cgshsl']

const createEmptyMetrics = () => ({
  mnjyzl: 0,
  jdjyzl: 0,
  xsshsl: 0,
  cgshsl: 0
})

const statsData = reactive({
  ...createEmptyMetrics(),
  systemStatus: '加载中...'
})

const allDimensionData = reactive({
  day: createEmptyMetrics(),
  week: createEmptyMetrics(),
  month: createEmptyMetrics()
})

const formatNumber = (num) => {
  return dataManager.formatNumber(num)
}

const API_URL = '/api/dashboard/real-time-stats'

const applyStats = (source) => {
  timeDimensions.forEach(({ key }) => {
    const item = source?.[key] || createEmptyMetrics()
    const next = createEmptyMetrics()
    metricKeys.forEach((metricKey) => {
      next[metricKey] = Number(item[metricKey]) || 0
    })
    allDimensionData[key] = next
  })
}

const loadData = async () => {
  try {
    statsData.systemStatus = '加载中...'
    const response = await fetch(API_URL)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const result = await response.json()
    if (result.code !== 1 || !result.data) {
      throw new Error(result.message || '接口返回异常')
    }

    applyStats(result.data)
    updateCurrentData()
    statsData.systemStatus = '数据加载完成'
  } catch (error) {
    console.error('加载实时统计数据失败:', error)
    statsData.systemStatus = '加载失败'
  }
}

const updateCurrentData = () => {
  const currentData = allDimensionData[currentDimension.value]
  if (currentData) {
    metricKeys.forEach((metricKey) => {
      statsData[metricKey] = currentData[metricKey]
    })
  }
}

watch(currentDimension, () => {
  updateCurrentData()
}, { immediate: false })

onMounted(async () => {
  await loadData()

  window.addEventListener('dataReloaded', async () => {
    await loadData()
  })
})
</script>

<style scoped>
.stats-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 14px 18px;
  flex: 1;
  min-height: 0;
  padding: 6px 10px 10px;
  align-items: center;
  justify-items: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  min-width: 0;
  width: 200px;
}

.stat-visual {
  position: relative;
  width: 200px;
  height: 129px;
  flex-shrink: 0;
}

.stat-platform {
  display: block;
  width: 200px;
  height: 129px;
  object-fit: fill;
  pointer-events: none;
  user-select: none;
}

.stat-value {
  position: absolute;
  left: 50%;
  top: 14px;
  transform: translateX(-50%);
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  text-align: center;
  pointer-events: none;
}

.stat-number {
  font-family: 'Arial Black', 'Microsoft YaHei', sans-serif;
  font-size: 30px;
  font-weight: 700;
  font-style: italic;
  line-height: 1;
  letter-spacing: 1px;
  transform: skewX(-6deg);
  background: linear-gradient(180deg, #c8ffff 0%, #00f2fe 48%, #00c4dc 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
  filter: drop-shadow(0 0 5px rgba(0, 242, 254, 0.75));
}

.stat-unit {
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 16px;
  font-weight: 700;
  line-height: 1;
  color: #ffffff;
  letter-spacing: 0;
}

.stat-label {
  margin-top: 10px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 18px;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0;
  white-space: nowrap;
  text-align: center;
  background: linear-gradient(180deg, #ffffff 0%, #e8f9ff 60%, #a8ecff 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
}
</style>
