<template>
  <div class="statistics-overview">
    <!-- 数据卡片 -->
    <a-space direction="vertical" size="large" fill>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>订单总额</template>
            <a-statistic
              :value="overviewData.totalOrderAmount"
              :precision="2"
              animation
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>成功订单总额</template>
            <a-statistic
              :value="overviewData.totalOrderAmountSuccess"
              :precision="2"
              animation
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>成功订单数</template>
            <a-statistic
              :value="overviewData.totalOrderCountSuccess"
              animation
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>活跃账号数</template>
            <a-statistic
              :value="overviewData.totalActiveAccountCount"
              animation
            />
          </a-card>
        </a-col>
      </a-row>

      <!-- 图表区域 -->
      <a-row :gutter="16">
        <a-col :span="24">
          <a-card class="chart-card general-card">
            <template #title>订单趋势</template>
            <v-chart class="chart" :option="orderTrendOption" autoresize />
          </a-card>
        </a-col>
        <!-- <a-col :span="12">
          <a-card class="chart-card general-card">
            <template #title>订单状态分布</template>
            <v-chart class="chart" :option="orderStatusOption" autoresize />
          </a-card>
        </a-col> -->
      </a-row>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, PieChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
import { apiClient } from '@/api/index.ts';
import { Message } from '@arco-design/web-vue';
import { KamiApiCardInfoWalmartV1StatsOverviewRes } from '@/api/generated';
import type { KamiApiCardInfoWalmartV1OrderSummaryRecord } from '@/api/generated';
import { formatDate } from '@vueuse/core';
import useChartOption from '@/hooks/chart-option';
import { EChartsOption, LegendComponentOption } from 'echarts';
import { maxBy } from 'lodash';
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
]);

const props = defineProps<{
  groupId?: number;
}>();

const overviewData = ref<KamiApiCardInfoWalmartV1StatsOverviewRes>({
  totalActiveAccountCount: 0,
  totalAccountCount: 0,
  totalOrderAmount: 0,
  totalOrderAmountSuccess: 0,
  totalOrderCount: 0,
  totalOrderCountSuccess: 0
});

// 订单趋势图表配置
const orderTrendOption = ref({
  legend: {
    show: true,
    textStyle: {
      color: '#4E5969'
    },
    selectedMode: 'multiple',
    data: ['订单数', '订单金额']
  } as LegendComponentOption,
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      show: true
    },
    axisTick: {
      show: true
    }
  },
  tooltip: {
    trigger: 'axis'
  },
  yAxis: [
    {
      type: 'value',
      name: '订单数',
      axisLine: {
        show: false
      },
      axisLabel: {
        show: true // 隐藏 y 轴标签
      }
    },
    {
      type: 'value',
      name: '金额',
      axisLine: {
        show: false
      },
      axisLabel: {
        show: true // 隐藏 y 轴标签
      }
    }
  ],
  series: [
    {
      name: '订单数',
      type: 'line',
      max: 0,
      data: []
    },
    {
      name: '订单金额',
      type: 'line',
      max: 0,
      data: []
    }
  ]
});

// 订单状态分布图表配置
const orderStatusOption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
});

// 获取概览数据
const fetchOverviewData = async () => {
  try {
    const res = await apiClient.apiCardInfoWalmartStatsOverviewGet({
      groupId: props.groupId
    });
    overviewData.value = res.data;

    // 更新图表数据
  } catch (error) {
    Message.error('获取统计数据失败');
  }
};

const fetchOrderTrendData = async () => {
  try {
    const res = await apiClient.apiCardInfoWalmartOrderSummaryGet({
      groupId: props.groupId
    });
    updateCharts(res.data.list);
  } catch (error) {
    Message.error('获取订单趋势数据失败');
  }
};

// 更新图表数据
const updateCharts = (data: KamiApiCardInfoWalmartV1OrderSummaryRecord[]) => {
  // 更新订单趋势图表
  orderTrendOption.value.xAxis.data = data.map(item =>
    formatDate(new Date(item.date), 'YY-MM-DD')
  );
  orderTrendOption.value.series[0].data = data.map(item => item.count);
  orderTrendOption.value.series[0].max = maxBy(data, 'amount')?.count || 0;
  orderTrendOption.value.series[1].data = data.map(item => item.amount);
  orderTrendOption.value.series[1].max = maxBy(data, 'amount')?.amount || 0;
  console.log(orderTrendOption.value.series);
  // // 更新订单状态分布图表
  // orderStatusOption.value.series[0].data = data.statusDistribution;
};

onMounted(() => {
  fetchOverviewData();
  fetchOrderTrendData();
});
</script>

<style scoped>
.statistics-overview {
  padding: 16px;
}

.stat-card {
  height: 100%;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1.5;
}

.chart-card {
  height: 100%;
}

.chart {
  height: 400px;
}

.download-container {
  margin-top: 16px;
  text-align: right;
}

.text-primary {
  color: rgb(var(--primary-6));
}

.text-success {
  color: rgb(var(--success-6));
}

.text-warning {
  color: rgb(var(--warning-6));
}

.text-info {
  color: rgb(var(--info-6));
}
</style>
