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

import { onMounted, ref } from 'vue';

import {
  AnalysisChartCard,
  AnalysisChartsTabs,
} from '@vben/common-ui';
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';
import AnalyticsProfitPanel from './analytics-profit-panel.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 chartTabs: TabOption[] = [
  {
    label: '订单趋势',
    value: 'order',
  },
  {
    label: '营收趋势',
    value: 'revenue',
  },
];

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

<template>
  <div class="p-5 dashboard-wrapper">
    <a-spin :spinning="loading">
      <div v-if="statistics" class="dashboard-container">
        <!-- 左侧：统计卡片和图表 -->
        <div class="dashboard-main">
          <!-- 合并后的统计卡片 -->
          <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <!-- 订单统计卡片 -->
            <AnalysisChartCard title="订单统计">
              <div class="py-2">
                <!-- 今日数据 -->
                <div class="mb-3">
                  <div class="text-xs text-gray-500 mb-1">今日订单</div>
                  <div class="flex items-baseline justify-between">
                    <div class="text-3xl font-bold text-blue-600">
                      {{ statistics.order_stats.today_count }}<span
                        class="text-lg font-normal ml-1 text-gray-500">单</span>
                    </div>
                    <div class="text-xs" v-if="statistics.order_stats.change_rate">
                      <span :class="statistics.order_stats.change_rate > 0 ? 'text-green-500' : 'text-red-500'">
                        {{ statistics.order_stats.change_rate > 0 ? '↑' : '↓' }} {{
                          Math.abs(statistics.order_stats.change_rate).toFixed(1) }}%
                      </span>
                    </div>
                  </div>
                </div>
                <!-- 当月和总计 - 两列布局 -->
                <div class="grid grid-cols-2 gap-3 pt-3 border-t">
                  <div>
                    <div class="text-xs text-gray-500 mb-1">当月</div>
                    <div class="text-lg font-semibold text-gray-700">
                      {{ formatNumber(statistics.order_stats.month_count) }}<span
                        class="text-sm font-normal text-gray-500 ml-1">单</span>
                    </div>
                  </div>
                  <div>
                    <div class="text-xs text-gray-500 mb-1">总计</div>
                    <div class="text-lg font-semibold text-gray-700">
                      {{ formatNumber(statistics.order_stats.total_count) }}<span
                        class="text-sm font-normal text-gray-500 ml-1">单</span>
                    </div>
                  </div>
                </div>
              </div>
            </AnalysisChartCard>

            <!-- 代理统计卡片 -->
            <AnalysisChartCard title="代理统计">
              <div class="py-2">
                <!-- 总数数据 -->
                <div class="mb-3">
                  <div class="text-xs text-gray-500 mb-1">代理总数</div>
                  <div class="text-3xl font-bold text-purple-600">
                    {{ statistics.agent_stats.total_count }}<span
                      class="text-lg font-normal ml-1 text-gray-500">人</span>
                  </div>
                </div>
                <!-- 新增数据 - 两列布局 -->
                <div class="grid grid-cols-2 gap-3 pt-3 border-t">
                  <div>
                    <div class="text-xs text-gray-500 mb-1">今日新增</div>
                    <div class="text-lg font-semibold text-gray-700">
                      {{ statistics.agent_stats.today_new }}<span
                        class="text-sm font-normal text-gray-500 ml-1">人</span>
                    </div>
                  </div>
                  <div>
                    <div class="text-xs text-gray-500 mb-1">当月新增</div>
                    <div class="text-lg font-semibold text-gray-700">
                      {{ statistics.agent_stats.month_new }}<span
                        class="text-sm font-normal text-gray-500 ml-1">人</span>
                    </div>
                  </div>
                </div>
              </div>
            </AnalysisChartCard>

          </div>

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

        <!-- 右侧：收入统计面板 -->
        <div class="dashboard-sidebar">
          <AnalyticsProfitPanel :profit-stats="statistics.profit_stats" />
        </div>
      </div>
    </a-spin>
  </div>
</template>

<style scoped lang="less">
.dashboard-wrapper {
  /* 让整个页面区域占满视口高度，方便右侧面板自适应 */
  min-height: 100vh;
  box-sizing: border-box;
}

.dashboard-container {
  display: flex;
  gap: 16px;
  align-items: flex-start;

  .dashboard-main {
    flex: 1;
    min-width: 0;
  }

  .dashboard-sidebar {
    /* 右侧面板根据视口高度拉满，高度=视口高度-上下padding(假设24px) */
    width: 800px;
    flex-shrink: 0;
    position: sticky;
    top: 16px;
    max-height: calc(100vh - 32px);
    overflow: auto;
  }
}

@media (max-width: 1600px) {
  .dashboard-container {
    flex-direction: column;

    .dashboard-sidebar {
      width: 100%;
      position: static;
      max-height: none;
      overflow: visible;
    }
  }
}
</style>
