<template>
  <view class="page">
    <!-- 导航栏 -->
    <NavBar title="数据统计" :showBack="true" />

    <!-- 时间筛选 -->
    <view class="time-filter">
      <view
        class="filter-btn"
        v-for="item in timeOptions"
        :key="item.value"
        :class="{ active: currentTime === item.value }"
        @click="changeTimeRange(item.value)"
      >
        <text>{{ item.label }}</text>
      </view>
    </view>

    <!-- 核心指标 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card primary">
          <text class="stat-label">销售额</text>
          <text class="stat-value">¥{{ formatMoney(overview.totalSales || 0) }}</text>
          <text class="stat-trend" v-if="overview.salesTrend">
            环比 {{ getTrendText(overview.salesTrend) }}
          </text>
        </view>
        <view class="stat-card">
          <text class="stat-label">订单数</text>
          <text class="stat-value">{{ overview.totalOrders || 0 }}</text>
        </view>
        <view class="stat-card">
          <text class="stat-label">客单价</text>
          <text class="stat-value">¥{{ formatMoney(overview.avgOrderAmount || 0) }}</text>
        </view>
        <view class="stat-card">
          <text class="stat-label">新增客户</text>
          <text class="stat-value">{{ overview.newUsers || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 商品销售排行 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">商品销售TOP10</text>
      </view>
      <view class="rank-card">
        <view
          class="rank-item"
          v-for="(item, index) in productTopList"
          :key="item.productId || index"
        >
          <view class="rank-num" :class="{ top: index < 3 }">
            <text>{{ index + 1 }}</text>
          </view>
          <view class="rank-info">
            <text class="rank-name">{{ item.productName || '未知商品' }}</text>
            <text class="rank-meta">{{ item.category || '未分类' }} · 销量 {{ item.quantity || 0 }}</text>
          </view>
          <view class="rank-value">
            <text class="rank-amount">¥{{ formatMoney(item.salesAmount || 0) }}</text>
          </view>
        </view>
        <view class="empty-mini" v-if="productTopList.length === 0">
          <text>暂无数据</text>
        </view>
      </view>
    </view>

    <!-- 门店业绩排行 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">门店业绩TOP10</text>
      </view>
      <view class="rank-card">
        <view
          class="rank-item"
          v-for="(item, index) in shopRankingList"
          :key="item.shopId || index"
        >
          <view class="rank-num" :class="{ top: index < 3 }">
            <text>{{ index + 1 }}</text>
          </view>
          <view class="rank-info">
            <text class="rank-name">{{ item.shopName || '未知门店' }}</text>
            <text class="rank-meta">订单 {{ item.orderCount || 0 }} · 客单 ¥{{ formatMoney(item.avgOrderAmount || 0) }}</text>
          </view>
          <view class="rank-value">
            <text class="rank-amount">¥{{ formatMoney(item.salesAmount || 0) }}</text>
          </view>
        </view>
        <view class="empty-mini" v-if="shopRankingList.length === 0">
          <text>暂无数据</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import { getStatisticsOverview, getProductTop, getShopRanking } from '@/api/statistics';
import { formatMoney as formatMoneyUtil } from '@/utils/common';

const loading = ref(false);
const currentTime = ref('week');
const overview = ref<any>({});
const productTopList = ref<any[]>([]);
const shopRankingList = ref<any[]>([]);

const timeOptions = [
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' }
];

const formatMoney = formatMoneyUtil;

const getDateRange = (type: string) => {
  const now = new Date();
  const endDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
  let startDate = endDate;

  if (type === 'today') {
    startDate = endDate;
  } else if (type === 'week') {
    const weekAgo = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000);
    startDate = `${weekAgo.getFullYear()}-${String(weekAgo.getMonth() + 1).padStart(2, '0')}-${String(weekAgo.getDate()).padStart(2, '0')}`;
  } else if (type === 'month') {
    const monthAgo = new Date(now.getTime() - 29 * 24 * 60 * 60 * 1000);
    startDate = `${monthAgo.getFullYear()}-${String(monthAgo.getMonth() + 1).padStart(2, '0')}-${String(monthAgo.getDate()).padStart(2, '0')}`;
  }

  return { startDate, endDate };
};

const getTrendText = (trend: any) => {
  if (!trend || !Array.isArray(trend) || trend.length < 2) return '-';
  const current = trend[trend.length - 1]?.value || 0;
  const prev = trend[trend.length - 2]?.value || 0;
  if (prev === 0) return '-';
  const change = ((current - prev) / prev * 100).toFixed(1);
  return `${change}%`;
};

const changeTimeRange = (type: string) => {
  currentTime.value = type;
  loadData();
};

const loadData = async () => {
  loading.value = true;
  const { startDate, endDate } = getDateRange(currentTime.value);

  try {
    const [overviewRes, productRes, shopRes] = await Promise.all([
      getStatisticsOverview({ startDate, endDate }),
      getProductTop({ startDate, endDate, type: currentTime.value, limit: 10 }),
      getShopRanking({ startDate, endDate, type: currentTime.value, limit: 10 })
    ]);

    overview.value = overviewRes || {};
    productTopList.value = Array.isArray(productRes) ? productRes : (productRes?.list || []);
    shopRankingList.value = Array.isArray(shopRes) ? shopRes : (shopRes?.list || []);
  } catch (error) {
    logger.warn('加载统计数据失败', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
  padding-bottom: 40rpx;
}

/* 时间筛选 */
.time-filter {
  display: flex;
  padding: 16rpx 24rpx;
  gap: 12rpx;
  background: $bg-color-card;
  border-bottom: 1rpx solid $border-color;

  .filter-btn {
    padding: 12rpx 28rpx;
    background: $bg-color-page;
    border: 2rpx solid $border-color;
    border-radius: 20rpx;
    font-size: 26rpx;
    color: $text-color-tertiary;
    transition: all 0.15s;

    &.active {
      background: $success-color-bg;
      border-color: $primary-color;
      color: $primary-color;
      font-weight: 500;
    }
  }
}

/* 核心指标 */
.stats-section {
  padding: 16rpx 24rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12rpx;
}

.stat-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 16rpx;
  padding: 24rpx 20rpx;
  display: flex;
  flex-direction: column;

  &.primary {
    background: $success-color-bg;
    border-color: $primary-color;
  }

  .stat-label {
    font-size: 22rpx;
    color: $text-color-muted;
    margin-bottom: 8rpx;
  }

  .stat-value {
    font-size: 36rpx;
    font-weight: 700;
    color: $text-color-primary;
    margin-bottom: 4rpx;
  }

  .stat-trend {
    font-size: 20rpx;
    color: $primary-color;
  }
}

/* 排行区域 */
.section {
  padding: 0 24rpx;
  margin-bottom: 16rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
  padding: 8rpx 0;

  .section-title {
    font-size: 30rpx;
    font-weight: 600;
    color: $text-color-primary;
  }
}

.rank-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 16rpx;
  padding: 8rpx 16rpx;
}

.rank-item {
  display: flex;
  align-items: center;
  padding: 16rpx 8rpx;
  border-bottom: 1rpx solid $bg-color-secondary;

  &:last-child {
    border-bottom: none;
  }
}

.rank-num {
  width: 44rpx;
  height: 44rpx;
  border-radius: 12rpx;
  background: $bg-color-secondary;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
  flex-shrink: 0;

  text {
    font-size: 24rpx;
    font-weight: 600;
    color: $text-color-muted;
  }

  &.top {
    background: $primary-color;

    text {
      color: #fff;
    }
  }
}

.rank-info {
  flex: 1;
  min-width: 0;

  .rank-name {
    display: block;
    font-size: 28rpx;
    color: $text-color-primary;
    font-weight: 500;
    margin-bottom: 4rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .rank-meta {
    font-size: 22rpx;
    color: $text-color-muted;
  }
}

.rank-value {
  flex-shrink: 0;
  margin-left: 12rpx;

  .rank-amount {
    font-size: 28rpx;
    font-weight: 600;
    color: $accent-color;
  }
}

.empty-mini {
  text-align: center;
  padding: 40rpx 0;
  font-size: 26rpx;
  color: $text-color-muted;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: $text-color-muted;
  font-size: 28rpx;

  .loading-spinner {
    width: 48rpx;
    height: 48rpx;
    border: 4rpx solid $border-color;
    border-top-color: $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16rpx;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>
