<template>
  <div class="stats-view">
    <!-- 概览卡片 -->
    <div class="overview-cards">
      <el-card class="overview-card" shadow="never">
        <div class="overview-value primary">{{ stats.todaySearches }}</div>
        <div class="overview-label">今日搜索</div>
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="overview-value success">{{ stats.todaySaves }}</div>
        <div class="overview-label">今日保存</div>
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="overview-value primary">{{ stats.monthSearches }}</div>
        <div class="overview-label">本月搜索</div>
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="overview-value success">{{ stats.monthSaves }}</div>
        <div class="overview-label">本月保存</div>
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="overview-value info">{{ stats.totalSearches }}</div>
        <div class="overview-label">总搜索量</div>
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="overview-value warning">{{ stats.totalSaves }}</div>
        <div class="overview-label">总保存量</div>
      </el-card>
    </div>

    <div class="stats-grid">
      <!-- 近7天趋势 -->
      <el-card class="stats-card" shadow="never">
        <template #header>
          <span>📈 近 7 天趋势</span>
        </template>
        <el-table :data="stats.trendTrend" stripe size="small" style="width: 100%">
          <el-table-column label="日期" min-width="120">
            <template #default="{ row }">
              {{ formatDate(row.date) }}
            </template>
          </el-table-column>
          <el-table-column label="搜索" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small" type="primary" effect="plain">{{ row.searches }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="保存" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small" type="success" effect="plain">{{ row.saves }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="趋势" min-width="150">
            <template #default="{ row }">
              <div class="trend-bar-wrap">
                <div class="trend-bar" :style="{ width: trendBarWidth(row) + '%', background: trendBarColor(row) }"></div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 热门搜索关键词 -->
      <el-card class="stats-card" shadow="never">
        <template #header>
          <span>🔥 热门搜索关键词 Top 20</span>
        </template>
        <el-table :data="stats.hotKeywords" stripe size="small" style="width: 100%" :max-height="480">
          <el-table-column type="index" label="排名" width="60" />
          <el-table-column prop="keyword" label="关键词" min-width="200" />
          <el-table-column prop="count" label="搜索次数" width="120" align="center">
            <template #default="{ row }">
              <el-tag>{{ row.count }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="stats.hotKeywords.length === 0" description="暂无数据" :image-size="60" />
      </el-card>

      <!-- 网盘使用空间 -->
      <el-card class="stats-card" shadow="never">
        <template #header>
          <span>💾 网盘使用空间</span>
        </template>
        <div v-for="item in stats.cloudUsage" :key="item.cloudType" class="storage-item">
          <div class="storage-header">
            <span class="storage-label">{{ item.nickname || item.cloudType }}</span>
            <span class="storage-badge" :class="item.isActive ? 'active' : 'inactive'">{{ item.isActive ? '正常' : '停用' }}</span>
          </div>
          <div class="storage-detail">
            <span class="storage-usage">{{ item.storageUsed || '未知' }} / {{ item.storageTotal || '未知' }}</span>
            <span class="storage-pct">{{ storagePercent(item) }}%</span>
          </div>
          <el-progress :percentage="storagePercent(item)" :stroke-width="14" :color="storagePercent(item) > 80 ? '#f56c6c' : '#67c23a'" />
        </div>
        <el-empty v-if="stats.cloudUsage.length === 0" description="暂无网盘数据" :image-size="60" />
      </el-card>

      <!-- 保存操作来源 IP Top 10 -->
      <el-card class="stats-card" shadow="never">
        <template #header>
          <span>🌐 保存操作来源 IP Top 10</span>
        </template>
        <el-table :data="stats.topIps" stripe size="small" style="width: 100%">
          <el-table-column type="index" label="排名" width="60" />
          <el-table-column prop="ip" label="IP" min-width="160">
            <template #default="{ row }">
              <span style="font-family: monospace; font-size: 12px">{{ row.ip }}</span>
            </template>
          </el-table-column>
          <el-table-column label="访问地址" min-width="160">
            <template #default="{ row }">
              <span v-if="row.ip_location" style="font-size: 12px">{{ formatLocation(row.ip_location) }}</span>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="操作次数" width="100" align="center">
            <template #default="{ row }">
              <el-tag type="warning" effect="plain">{{ row.count }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="stats.topIps.length === 0" description="暂无数据" :image-size="60" />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getStats } from '../../api'
import type { StatsData } from '../../types'

const stats = ref<StatsData>({
  todaySearches: 0,
  todaySaves: 0,
  monthSearches: 0,
  monthSaves: 0,
  totalSearches: 0,
  totalSaves: 0,
  hotKeywords: [],
  trendTrend: [],
  cloudUsage: [],
  topIps: [],
  provinceRankings: [],
})

onMounted(async () => {
  try {
    stats.value = await getStats()
  } catch (e) {
    console.error('加载统计数据失败', e)
  }
})

function formatDate(d: string): string {
  if (!d) return '-'
  return d.split(' ')[0] || d
}

/** Strip "中国/China" prefix from location string for consistent display */
function formatLocation(loc: string): string {
  if (!loc) return ''
  return loc.replace(/^(中国|China)\s*/i, '').trim()
}

function storagePercent(item: { storageUsed: string; storageTotal: string }): number {
  if (!item.storageUsed || !item.storageTotal) return 0
  const used = parseFloat(item.storageUsed)
  const total = parseFloat(item.storageTotal)
  if (total <= 0) return 0
  return Math.round((used / total) * 100)
}

/// 趋势条宽度（基于当日搜索+保存之和）
function trendBarWidth(row: { searches: number; saves: number }): number {
  const max = Math.max(...stats.value.trendTrend.map(r => r.searches + r.saves), 1)
  return ((row.searches + row.saves) / max) * 100
}
function trendBarColor(row: { searches: number; saves: number }): string {
  const total = row.searches + row.saves
  if (total === 0) return '#ebeef5'
  // Color gradient: more saves → more green
  const ratio = row.saves / Math.max(total, 1)
  if (ratio > 0.5) return '#67c23a'
  if (ratio > 0.2) return '#409eff'
  return '#909399'
}
</script>

<style scoped>
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

/* --- 概览卡片：阴影 + 悬浮 + 渐变底色 --- */
.overview-card {
  border: none !important;
  border-radius: 12px !important;
  background: linear-gradient(135deg, #ffffff 0%, #f8faff 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}
.overview-card :deep(.el-card__body) {
  text-align: center;
  padding: 22px 16px;
  background: transparent !important;
}
.overview-value {
  font-size: 36px;
  font-weight: 700;
  margin-bottom: 6px;
}
.overview-value.primary { color: var(--el-color-primary); }
.overview-value.success { color: var(--el-color-success); }
.overview-value.info    { color: var(--el-color-info); }
.overview-value.warning { color: var(--el-color-warning); }
.overview-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

/* --- stats-card 美化阴影和圆角 --- */
.stats-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.stats-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.3s ease;
  border: 1px solid var(--el-border-color-light, #ebeef5);
}
.stats-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.09);
}
.stats-card :deep(.el-card__header) {
  padding: 12px 16px;
  font-size: 15px;
  font-weight: 600;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: linear-gradient(90deg, #fafbfc 0%, #ffffff 100%);
}

/* --- 表格行 hover 高亮 --- */
.stats-view :deep(.el-table__body tr:hover > td.el-table__cell) {
  background-color: #ecf5ff !important;
  cursor: default;
}
.stats-view :deep(.el-table__body tr) {
  transition: background-color 0.2s ease;
}

/* --- 趋势条 --- */
.trend-bar-wrap {
  height: 16px;
  background: #f0f2f5;
  border-radius: 8px;
  overflow: hidden;
}
.trend-bar {
  height: 100%;
  border-radius: 8px;
  transition: width .3s;
  min-width: 4px;
}

/* --- 存储进度条更圆润 --- */
.stats-view :deep(.el-progress-bar__outer) {
  border-radius: 99px !important;
  overflow: hidden;
}
.stats-view :deep(.el-progress-bar__inner) {
  border-radius: 99px !important;
}
.storage-item {
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}
.storage-item:last-child {
  border-bottom: none;
}
.storage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}
.storage-label {
  font-size: 14px;
  font-weight: 500;
}
.storage-badge {
  font-size: 11px;
  padding: 1px 8px;
  border-radius: 4px;
}
.storage-badge.active { background: #f0f9eb; color: #67c23a; }
.storage-badge.inactive { background: #fef0f0; color: #f56c6c; }
.storage-detail {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 6px;
}
.storage-pct {
  font-weight: 600;
}
</style>
