<script lang="ts" setup>
import type { AnalysisOverviewItem } from '@vben/common-ui';
import type { TabOption } from '@vben/types';

import { computed, onMounted, ref } from 'vue';

import {
  AnalysisChartCard,
  AnalysisChartsTabs,
  AnalysisOverview,
} from '@vben/common-ui';
import {
  SvgBellIcon,
  SvgCakeIcon,
  SvgCardIcon,
  SvgDownloadIcon,
} from '@vben/icons';
import { message } from 'ant-design-vue';

import { getDashboardStatistics } from '#/api/dashboard';
import type { DashboardApi } from '#/api/dashboard';

import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsRevenueTrend from './analytics-revenue-trend.vue';

const loading = ref(false);
const statistics = ref<DashboardApi.DashboardStatistics | null>(null);

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount >= 10000) {
    return `${(amount / 10000).toFixed(2)}万`;
  }
  return amount.toFixed(2);
};

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return `${(num / 10000).toFixed(2)}万`;
  }
  return num.toString();
};

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true;
  try {
    const data = await getDashboardStatistics();
    statistics.value = data;
  } catch (error) {
    message.error('加载统计数据失败');
  } finally {
    loading.value = false;
  }
};

// 计算概览卡片数据
const overviewItems = computed<AnalysisOverviewItem[]>(() => {
  if (!statistics.value) {
    return [];
  }

  const { order_stats, revenue_stats, agent_stats, profit_stats } =
    statistics.value;

  return [
    {
      icon: SvgCardIcon,
      title: '今日订单',
      totalTitle: '总订单',
      totalValue: order_stats.total_count,
      value: order_stats.today_count,
      suffix: order_stats.change_rate
        ? ` ${order_stats.change_rate > 0 ? '↑' : '↓'} ${Math.abs(
          order_stats.change_rate,
        ).toFixed(1)}%`
        : '',
    },
    {
      icon: SvgCakeIcon,
      title: '今日营收',
      totalTitle: '总营收',
      totalValue: revenue_stats.total_amount,
      value: revenue_stats.today_amount,
      suffix: revenue_stats.change_rate
        ? ` ${revenue_stats.change_rate > 0 ? '↑' : '↓'} ${Math.abs(
          revenue_stats.change_rate,
        ).toFixed(1)}%`
        : '',
    },
    {
      icon: SvgBellIcon,
      title: '代理总数',
      totalTitle: '代理总数',
      totalValue: agent_stats.total_count,
      value: agent_stats.today_new,
      suffix: ` 今日新增: ${agent_stats.today_new}`,
    },
    {
      icon: SvgDownloadIcon,
      title: '今日利润',
      totalTitle: '总利润',
      totalValue: profit_stats.total_profit,
      value: profit_stats.today_profit,
      suffix: ` 利润率: ${profit_stats.today_profit_rate.toFixed(1)}%`,
    },
  ];
});

const chartTabs: TabOption[] = [
  {
    label: '订单趋势',
    value: 'order',
  },
  {
    label: '营收趋势',
    value: 'revenue',
  },
];

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

<template>
  <div class="p-5">
    <a-spin :spinning="loading">
      <div v-if="statistics">
        <!-- 统计卡片 -->
        <AnalysisOverview :items="overviewItems" />

        <!-- 趋势图表 -->
        <AnalysisChartsTabs :tabs="chartTabs" class="mt-5">
          <template #order>
            <AnalyticsTrends :data="statistics.order_trend" />
          </template>
          <template #revenue>
            <AnalyticsRevenueTrend :data="statistics.revenue_trend" />
          </template>
        </AnalysisChartsTabs>

        <!-- 详细统计信息 -->
        <div class="mt-5 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
          <!-- 订单统计卡片 -->
          <AnalysisChartCard title="订单统计">
            <div class="space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">今日订单:</span>
                <span class="font-semibold">{{ statistics.order_stats.today_count }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当月订单:</span>
                <span class="font-semibold">{{ formatNumber(statistics.order_stats.month_count) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">总订单:</span>
                <span class="font-semibold">{{ formatNumber(statistics.order_stats.total_count) }}</span>
              </div>
            </div>
          </AnalysisChartCard>

          <!-- 营收统计卡片 -->
          <AnalysisChartCard title="营收统计">
            <div class="space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">今日营收:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.revenue_stats.today_amount) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当月营收:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.revenue_stats.month_amount) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">总营收:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.revenue_stats.total_amount) }}</span>
              </div>
            </div>
          </AnalysisChartCard>

          <!-- 代理统计卡片 -->
          <AnalysisChartCard title="代理统计">
            <div class="space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">代理总数:</span>
                <span class="font-semibold">{{ statistics.agent_stats.total_count }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">今日新增:</span>
                <span class="font-semibold">{{ statistics.agent_stats.today_new }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当月新增:</span>
                <span class="font-semibold">{{ statistics.agent_stats.month_new }}</span>
              </div>
            </div>
          </AnalysisChartCard>

          <!-- 利润统计卡片 -->
          <AnalysisChartCard title="利润统计">
            <div class="space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">今日利润:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.profit_stats.today_profit) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当月利润:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.profit_stats.month_profit) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">总利润:</span>
                <span class="font-semibold">¥{{ formatAmount(statistics.profit_stats.total_profit) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">利润率:</span>
                <span class="font-semibold">{{ statistics.profit_stats.total_profit_rate.toFixed(1) }}%</span>
              </div>
            </div>
          </AnalysisChartCard>
        </div>
      </div>
    </a-spin>
  </div>
</template>
