<template>
  <div class="statistics">
    <h1>统计分析</h1>
    <div class="cards">
      <div class="card" v-for="(item, index) in statistics" :key="index">
        <h2>{{ item.title }}</h2>
        <p class="val">{{ item.value }}</p>
      </div>
    </div>
    <div class="chart">
      <h2>全年销售额分析图</h2>
      <canvas ref="salesChart"></canvas>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted } from 'vue';
import { Chart, registerables } from 'chart.js';
import { getStatisticsData, getYearlySalesData } from '/@/api/mock'; 

// 定义统计项的类型
interface Statistic {
  title: string;
  value: string | number;
}

Chart.register(...registerables);

export default {
  name: 'Statistics',

  setup() {
    const statistics = ref<Statistic[]>([]); 
      const salesChart = ref<HTMLCanvasElement | null>(null);

    const fetchStatistics = async () => {
      const data = await getStatisticsData();
      statistics.value = [
        { title: '今日访问量', value: '+' + data.todayVisits },
        { title: '新增用户', value: '+' + data.newUsers },
        { title: '当月销售额', value: data.currentMonthSales },
        { title: '当月订单量', value: data.currentMonthOrders },
      ];
    };

    const fetchYearlySales = async () => {
      if (salesChart.value) {
        const ctx = salesChart.value.getContext('2d');
        const data = await getYearlySalesData();

        new Chart(ctx!, {
          type: 'line',
          data: {
            labels: [
              '一月', '二月', '三月', '四月', '五月', '六月',
              '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            datasets: [{
              label: '全年销售额',
              data: data.monthlySales,
              borderColor: 'rgba(75, 192, 192, 1)',
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderWidth: 1,
            }]
          },
          options: {
            responsive: true,
            scales: {
              y: {
                beginAtZero: true
              }
            }
          }
        });
      }
    };

    onMounted(async () => {
      await fetchStatistics();
      await fetchYearlySales();
    });

    return {
      statistics,
      salesChart
    };
  }
};
</script>

<style scoped>
.val {
    margin-top: 10px;
}

.statistics {
  padding: 20px;
}

.cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.card {
  flex: 1;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
}

.chart {
  margin-top: 20px;
}
</style>
