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

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

import { onMounted, ref } from 'vue';

import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsVisitsData from './analytics-visits-data.vue';
import AnalyticsVisitsSales from './analytics-visits-sales.vue';
import AnalyticsVisitsSource from './analytics-visits-source.vue';
import AnalyticsVisits from './analytics-visits.vue';

import { getAgentStatistics, getWithdrawalStatistics, getAgentOrderStatistics } from '#/api/agent';
import { getOrderList, getRefundStatistics, getIncomeStatistics } from '#/api/order/order';
import { getPlatformUserList } from '#/api/platform-user';

// 初始化概览数据
const overviewItems = ref<AnalysisOverviewItem[]>([
  {
    icon: SvgCardIcon,
    title: '总用户数',
    value: 0,
    todaytitle: '今日新增用户数',
    todayValue: 0,
    Subtitle: '总代理数',
    SubValue: 0,
    todaySubtitle: '今日新增代理数',
    todaySubValue: 0,
  },
  {
    icon: SvgCakeIcon,
    title: '总订单数',
    value: 0,
    todaytitle: '今日新增订单数',
    todayValue: 0,
    Subtitle: '代理总订单量',
    SubValue: 0,
    todaySubtitle: '今日新增代理订单量',
    todaySubValue: 0,
  },
  {
    icon: SvgDownloadIcon,
    title: '总收入流水金额',
    value: 0,
    todaytitle: '今日新增收入流水金额',
    todayValue: 0,
    Subtitle: '总利润',
    SubValue: 0,
    todaySubtitle: '今日新增利润',
    todaySubValue: 0,
  },
  {
    icon: SvgBellIcon,
        title: '总提现金额',
        value: 0,
        SubValue: 0,
        todaySubtitle: '总实际到账金额',
        todaySubValue: 0,
        extraTitle: '总扣税金额',
        extraValue: 0,
        todaytitle: '今日新增提现金额',
        todayValue: 0,
        Subtitle: '总退款金额',
        extra2Title: '今日新增退款金额',
        extra2Value: 0,
  },
]);

const chartTabs: TabOption[] = [
  {
    label: '订单趋势',
    value: 'visits',
  },
  {
    label: '推广访问趋势',
    value: 'trends',
  },
];

// 获取统计数据
async function fetchStatistics() {
  try {
    // 获取今日的开始和结束时间
    const today = new Date();
    // 将时间格式化为后端期望的格式 (YYYY-MM-DD HH:MM:SS)
    const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate()).toISOString().replace('T', ' ').substring(0, 19);
    const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1).toISOString().replace('T', ' ').substring(0, 19);
    
    // 获取平台用户数据（总数）
    const platformUserResponse = await getPlatformUserList({ page: 1, pageSize: 1 });
    const platformUserTotal = platformUserResponse.total || 0;
    
    // 获取今日新增用户数
    // 由于平台用户API不支持时间过滤，我们需要获取更多数据并在前端过滤
    const newUserResponse = await getPlatformUserList({ page: 1, pageSize: 1000 });
    const newUserCount = newUserResponse.items?.filter(user => {
      const userCreateTime = new Date(user.create_time);
      return userCreateTime >= new Date(startTime) && userCreateTime < new Date(endTime);
    }).length || 0;
    
    // 获取订单数据
    const orderResponse = await getOrderList({ page: 1, pageSize: 1 });
    const orderTotal = orderResponse.total || 0;
    
    // 获取代理订单数据
    const agentOrderResponse = await getAgentOrderStatistics();
    const agentOrderTotal = agentOrderResponse.total_agent_order_count || 0;
    
    // 获取今日新增订单数
    const todayOrderResponse = await getOrderList({ 
      page: 1, 
      pageSize: 1000,
      create_time_start: startTime,
      create_time_end: endTime
    });
    const todayOrderTotal = todayOrderResponse.total || 0;
    
    // 获取今日新增代理订单数
    const todayAgentOrderResponse = await getAgentOrderStatistics();
    const todayAgentOrderTotal = todayAgentOrderResponse.today_agent_order_count || 0;
    
    // Product data is no longer needed for order statistics
    
    // 获取代理统计数据
    const agentStatsResponse = await getAgentStatistics();
    const agentTotal = agentStatsResponse.total_agent_count || 0;
    const newAgentCount = agentStatsResponse.today_agent_count || 0;
    
    // 获取提现统计数据
    const withdrawalStatsResponse = await getWithdrawalStatistics();
    const totalWithdrawalAmount = withdrawalStatsResponse.total_withdrawal_amount || 0;
    const todayWithdrawalAmount = withdrawalStatsResponse.today_withdrawal_amount || 0;
    const totalActualAmount = withdrawalStatsResponse.total_actual_amount || 0;
    const totalTaxAmount = withdrawalStatsResponse.total_tax_amount || 0;
    
    // 获取退款统计数据
    const refundStatsResponse = await getRefundStatistics();
    const totalRefundAmount = refundStatsResponse.total_refund_amount || 0;
    const todayRefundAmount = refundStatsResponse.today_refund_amount || 0;
    
    // 获取收入统计数据
    const incomeStatsResponse = await getIncomeStatistics();
    const totalIncome = incomeStatsResponse.total_revenue_amount || 0;
    const todayIncome = incomeStatsResponse.today_revenue_amount || 0;
    const totalProfit = incomeStatsResponse.total_profit_amount || 0;
    const todayProfit = incomeStatsResponse.today_profit_amount || 0;
    
    // 更新概览数据
    overviewItems.value = [
      {
        icon: SvgCardIcon,
        title: '总用户数',
        value: platformUserTotal,
        todaytitle: '今日新增用户数',
        todayValue: newUserCount,
        Subtitle: '总代理数',
        SubValue: agentTotal,
        todaySubtitle: '今日新增代理数',
        todaySubValue: newAgentCount,
      },
      {
        icon: SvgCakeIcon,
        title: '总订单数',
        value: orderTotal,
        todaytitle: '今日新增订单数',
        todayValue: todayOrderTotal,
        Subtitle: '总代理订单量',
        SubValue: agentOrderTotal,
        todaySubtitle: '今日新增代理订单量',
        todaySubValue: todayAgentOrderTotal, 
      },
      {
        icon: SvgDownloadIcon,
        title: '总收入流水金额',
        value: totalIncome,
        todaytitle: '今日新增收入流水金额',
        todayValue: todayIncome,
        Subtitle: '总利润',
        SubValue: totalProfit,
        todaySubtitle: '今日新增利润',
        todaySubValue: todayProfit,
      },
      {
        icon: SvgBellIcon,
        title: '总提现金额',
        value: totalWithdrawalAmount,
        todaytitle: '今日新增提现金额',
        todayValue: todayWithdrawalAmount,
        extra2Title: '今日新增退款金额',
        extra2Value: todayRefundAmount,
        Subtitle: '总退款金额',
        SubValue: totalRefundAmount,
        todaySubtitle: '总实际到账金额',
        todaySubValue: totalActualAmount,
        extraTitle: '总扣税金额',
        extraValue: totalTaxAmount,
      },
    ];
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStatistics();
});
</script>

<template>
  <div class="p-5">
    <AnalysisOverview :items="overviewItems" />
    <AnalysisChartsTabs :tabs="chartTabs" class="mt-5">
      <template #visits>
        <AnalyticsVisits />
      </template>
      <template #trends>
        <AnalyticsTrends />
      </template>
    </AnalysisChartsTabs>

    <div class="mt-5 w-full md:flex">
      <AnalysisChartCard
        class="mt-5 md:mr-4 md:mt-0 md:w-1/3"
        title="推广数据分析"
      >
        <AnalyticsVisitsData />
      </AnalysisChartCard>
      <AnalysisChartCard
        class="mt-5 md:mr-4 md:mt-0 md:w-1/3"
        title="订单来源分析"
      >
        <AnalyticsVisitsSource />
      </AnalysisChartCard>
      <AnalysisChartCard
        class="mt-5 md:mt-0 md:w-1/3"
        title="佣金/奖励/提现统计"
      >
        <AnalyticsVisitsSales />
      </AnalysisChartCard>
    </div>
  </div>
</template>
